C struct initialization with char array
mike.name
is 20 bytes of reserved memory inside the struct. guest_name
is a pointer to another memory location. By trying to assign guest_name
to the struct's member you try something impossible.
If you have to copy data into the struct you have to use memcpy
and friends. In this case you need to handle the \0
terminator.
memcpy(mike.name, guest_name, 20);
mike.name[19] = 0; // ensure termination
If you have \0
terminated strings you can also use strcpy
, but since the name
's size is 20, I'd suggest strncpy
.
strncpy(mike.name, guest_name, 19);
mike.name[19] = 0; // ensure termination
mike.name is a character array. You can't copy arrays by just using the = operator.
Instead, you'll need to use strncpy
or something similar to copy the data.
int guest_age = 30;
char guest_name[20] = "Mike";
struct Guest mike = { guest_age };
strncpy(mike.name, guest_name, sizeof(mike.name) - 1);
You've tagged this question as C++, so I'd like to point out that in that case you should almost always use std::string
in preference to char[]
.