简体   繁体   中英

C struct initialization with pointer

I am kind of new to C and I cannot figure out why the following code is not working:

typedef struct{
    uint8_t a;
    uint8_t* b;
} test_struct;

test_struct test = {
    .a = 50,
    .b = {62, 33}
};

If I do this instead, it works:

int temp[] = {62, 33};

test_struct test = {
    .a = 50,
    .b = temp
};

The b member is not an array but a pointer. So when you attempt to initialize like this:

test_struct test = {
    .a = 50,
    .b = {62, 33}
};

You're setting test.b to the value 62 converted to a pointer, with the extra initializer discarded.

The second case works because you're initializing the b member with temp which is an int array which decays to a pointer to an int to match the type of the member b .

You could also do something like this and it would work:

test_struct test = {
    .a = 50,
    .b = (int []){62, 33}
};

However, the pointer to the compound literal will only be valid in the scope it was declared. So if you defined this struct inside of a function and returned a copy of it, the pointer would no longer be valid.

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