Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C struct initialization with pointer

Tags:

c

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
};
like image 672
Sara Smith Avatar asked Apr 22 '26 17:04

Sara Smith


1 Answers

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.

like image 194
dbush Avatar answered Apr 25 '26 11:04

dbush



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!