How to store string type data in a linked list in C

clinked listpointers

So I'm trying to understand how a linked list works with storing string type pieces of data. As far as I know, a linked list uses a data structure to store data in a somewhat fashionable way so you can easily enter new pieces of data inside, remove them, and rearrange them as you please. My problem is, I need to take a string in from the user, assign it a spot in the linked list and move on to the next node in the list and do the same thing again. At this point however, I'm simply trying to take one string from the user, store it in the new_node value, (or (*new_node).value for those of you thinking in terms of pointers and not linked lists) and print it out. The main just asks the user for a string input, the add_to_list func takes the input and adds it to the beginning of the linked list, and the print func simply prints what ever is in the linked list. Where the problem lies in my understanding (at least what I think is the problem) is the point at which I assign the data structure the value of the input, new_node->value=*n should just make the value contain the input string as it would just giving another array the value of whatever the pointer *n is containing, unfortunately that's not the case and I'm not sure why that is. Here's the code for simplicity's sake.

EDIT: Thanks everyone for the responses and the explanation behind why strcpy is necessary when dealing with assigning the value of an array of characters to another array ie: strings!

#include <stdio.h>
#include <stdlib.h>
#define LARGE 10

struct node *add_to_list(struct node *list, char *n);
struct node{
    char value[LARGE+1];
    struct node *next;
};

struct node *first = NULL;
void print(void);

int main(void) {
    
    char job[LARGE],*p;
    
    printf("Please enter printing jobs\n");
    scanf ("%s", job);
    p=&job[0];
    
    first = add_to_list(first, p);
    print();
    return 0;
}




struct node *add_to_list(struct node *list, char *n)
{
    struct node *new_node;
    new_node = malloc(sizeof(struct node));
    if (new_node == NULL) {
        printf("Error: malloc failed in add_to_list\n");
        exit(EXIT_FAILURE);
    }
    new_node->value = *n;
    new_node->next = list;
    return new_node;
}

void print(void){
    struct node *new_node;
    for(new_node=first;new_node!= NULL; new_node=new_node->next){
        printf("%s\n",new_node->value);
    }
}

Best Answer

Use strcpy instead of assigning a char to an array, which doesn't compile. Arrays are not lvalues, and cannot be assigned to without subscripting, so any assignment with an array name by itself on the left will not compile. Change

new_node->value = *n;

to

#include <string.h>

...

strcpy(new_node->value, n);
Related Topic