3

I have a the following struct

typedef struct mainstruct {
    uint32_t        var1;
    field_struct    var2[2];
    uint32_t        var3;
} main_struct;

where field_struct is :

typedef struct fieldstruct {
    uint8_t     var11[8];
    uint32_t    var22; 
    uint32_t    var33; 
    uint8_t     var44[16];
    uint8_t     var55[16];
    uint8_t     var66[16];
} field_struct;

How can I initialize all the field_struct field in main_struct to all zeroes ? Also var1 and var2 need to be initialized to specific values.

4
  • If you have a declaration with an initializer, e.g. main_struct ms = { .var1 = 1 };, then all unspecified fields will be initialized to zero. Commented Apr 25, 2019 at 6:57
  • @Lundin: fixed it in the meantime, thanks Commented Apr 25, 2019 at 6:58
  • main_struct ms = {42u, {{0}}, 7u}; Commented Apr 25, 2019 at 7:01
  • main_struct *m; memset(m->field_struct, 0, 2 * sizeof(field_struct)); Commented Apr 25, 2019 at 7:04

3 Answers 3

4

If you partially initialize the struct, the rest of the members that you don't initialize explicitly are set to zero. So it is enough to just initialize those members that need specific values:

main_struct ms = 
{
  .var1 = something,
  .var2 = { something_else },
};
Sign up to request clarification or add additional context in comments.

Comments

1

How can I initialize all the field_struct field in main_struct to all zeroes?

If you don't have access to designated initializers (C99 and C11), you can simply zero-initialize the entire struct and then initialize the rest to whatever you need:

main_struct s = {0};
s.var1 = ...;

The optimizer will do the right thing. Of course, if you don't want to initialize everything, you would have to manually initialize the ones you need only.

1 Comment

Because of a special case in the language to make initialization of scalars consistent, and the generously flexible rules for nested braces in initializers, = {0} can be used to correctly initialize any type in the language to its appropriate zero value.
0

If you're trying to set default values for struct members then you simply can't do it: structures are data types, not instances of data types.

Instead, if you only want to initialize the members of an instance of your data type then you can use the method described in Lundin's answer.

Comments

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.