简体   繁体   中英

Initialization of the structure containing pointer to another structure in C99

I've some structures definitions below :

typedef struct { 
  uint16_t a ;
} my_type1_t ;

typedef struct { 
  uint16_t b ; 
} my_type2_t ; 

typedef struct {
  my_type1_t* a_ptr ;
  my_type2_t* b_ptr ;
} both_t ; 

typedef struct {
  both_t* both_ptr ;
} gathered_t 

and some instances of the above structures :

my_type1_t a = { 
  .a = 0x01U,
} ;

my_type2_t b = { 
  .b = 0xAAU,
} ;

I'd like to ask is this possible in C99 standard or higher to do some initialization of the structure as below:

gathered_t all = {
  .both_ptr.a_ptr = &a,
  .both_ptr.b_ptr = &b,
};

I know that solution of this problem can be defining instance of the both_t structure, however this introduces additional object which consumes memory.

Since your structure declares a pointer type you'd have to allocate memory for the object somewhere. But you don't need to have to declare a variable for that, a compound literal would do:

gathered_t all = {
  .both_ptr = &(both_t){ 
     .a_ptr = &a,
     .b_ptr = &b,
   }
};

The compound literal is allocated according to the scope where this initialization is found; if it is at file scope the allocation would be static, otherwise it would be automatic (on the "stack");

Here, if you don't add any storage specifier to the declaration of all , this compound literal then would have the same lifetime as that variable.

No that is not possible. You will require memory for the both_t anyway. So the solution

both_t both = { &a, &b };
gathered_t all = { &both };

will use exactly as much memory as you expect.

See other answers to avoid the introduction of a new variable both , which show a new feature of C99 indeed.

Try this

gathered_t all = {
    .both_ptr = &(both_t){ &a, &b }
};

Full example at http://codepad.org/kGxiPPxT

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