namarino namarino - 3 months ago 33
C Question

Reading string into struct data in C

typedef struct Node {
char number[5];
struct Node *next;
} Node;

char userString[5];
scanf("%s", userString);

Node *newNode = malloc(sizeof(Node));
newNode->number = userString;

I'm trying to read a string entered by the user into "number" in the struct Node, but I'm getting an error that says "assignment to expression with array type". What I can do to fix this?


instead of

 newNode->number = userString;

Use strncpy()

 strncpy(newNode->number, userString,sizeof(newNode->number));

Reason why strcpy is needed : newnode->number = userSting , newnode->number is char[] type hence you need to loop and fill all the content byte by byte, while your statement is pointing to the string thats why compiler is giving "assignment to expression with array type"

Now why i have used the strncpy instead of strcpy ... because strncpy limits the bounds of copying.

I hope you understand.