3

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
};
1
  • 2
    What do you expect the second code to set the value of b to? A pointer to what exactly? In the second code, it's clear, it points to temp. What should the first code make b point to? Commented Aug 18, 2022 at 18:29

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

What's the lifetime of that inner .b value in the second example? Is it necessary to use a static variable?
@tadman The lifetime of a compound literal is that of its enclosing scope. So if test is declared at file scope then the compound literal has full program lifetime.
For sure, I just mean the context of where this code is used is relevant. Put this in a function and you're in for a surprise. It's worth mentioning as that kind of thing can trip you up if you're not expecting it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.