namarino namarino - 1 year ago 88
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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download