简体   繁体   中英

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 Guest 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 guest_name 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?

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[] .

Actually you can statically initialise this struct:

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

Guest guest = { 30, {'M','i','k','e','\0'}};

Each element of the array must be set explictly and this cannot be done using c-strings. If the struct is defined with a char* name then we can do this:

struct Guest {
   int age;
   char* name;
};

Guest guest = { 30, "Mike"};

You can statically allocate a struct with a fixed char[] array in C. For example, gcc allows the following:

#include <stdio.h>

typedef struct {
    int num;
    char str[];
} test;

int main(void) {
    static test x={.num=sizeof("hello"),.str="hello"};

    printf("sizeof=%zu num=%d str=%s\n",sizeof(x),x.num,x.str);
    return 0;
}

And it does the right thing (though beware of the sizeof(x): it returns 4 on my machine; not the length of the total statically allocated memory).

This does not work for structs allocated from the stack, as you might suspect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM