0

When I call strncpy() with an uninitialized string like this

strncpy(person->name, string, sizeof(person->name)); 

and then compile with -Wall and -Werror, and I see this error:

src/parser.c:18:35: error: argument to ‘sizeof’ in ‘strncpy’ call is the same expression as the destination; did you mean to provide an explicit length? [-Werror=sizeof-pointer-memaccess] strncpy(person->name, string, sizeof(person->name)); 

I see that some other posts mentioned array decay in C, is it the same thing in this case? What would be the correct way to use strncpy() in this function then?

Edit: first, I malloc'd the struct as well as the string, and then I called strncpy(). Here is what the struct looks like:

typedef struct { char *name; int age; int phone_num; } person_t; 
4
  • 3
    Ask yourself : "What is the value of sizeof(person->name);"? It isn't what you think it is. Once you see this, then ask "what function gives me the number of characters in the buffer?". Commented Apr 9, 2020 at 5:25
  • 3
    sizeof(person->name) == sizeof (char *), not sizeof(the number of bytes malloc-ed) Commented Apr 9, 2020 at 5:26
  • 1
    Neither of the duplicates are relevant, this question has nothing to do with strlen. Clearly the poster thinks that sizeof will give the size of the allocated block. Commented Apr 9, 2020 at 5:28
  • Would strncpy(person->name, string, strlen(string) + 1) work then? Commented Apr 9, 2020 at 5:34

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.