tonga tonga - 1 month ago 10x
C Question

C struct initialization with char array

I have a C struct defined as follows:

struct Guest {
int age;
char name[20];

When I created a
variable and initialized it using the following:

int guest_age = 30;
char guest_name[20] = "Mike";
struct Guest mike = {guest_age, guest_name};

I got the error about the second parameter initialization which tells me that
cannot be used to initialize member variable
char name[20]

I could do this to initialize all:

struct Guest mike = {guest_age, "Mike"};

But this is not I want. I want to initialize all fields by variables. How to do this in C?

Answer 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(, guest_name, 20);[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(, guest_name, 19);[19] = 0; // ensure termination