0
 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?

4
  • 1
    Use strcpy() to copy a string. Use %4s in the format string to prevent buffer overflow. Commented Dec 1, 2016 at 6:46
  • 2
    I would suggest strncpy() man page Commented Dec 1, 2016 at 6:51
  • 1
    Oh no, here we go again. Don't let cdlane here you suggest strncpy() the padding of the unused space in the array can get costly. Commented Dec 1, 2016 at 6:56
  • I would suggest properly formatting your code. But I must say... your post was adequately messy to serve as an example, so thank you for that. Commented Dec 1, 2016 at 8:10

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Can you explain why I have to use strcpy() instead of the way that I did it?
Thanks so much for the help!
2

you need to use strcpy function to correctly copy data from userString to your number array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.