Home > Back-end >  C struct initialization with pointer
C struct initialization with pointer

Time:08-21

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
};

CodePudding user response:

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.

  •  Tags:  
  • c
  • Related