2021-08-24

Initializing a structure in C language

#include <stdio.h>
typedef struct sub_struct {
int field1;
int field2;
int field3;
} SUB_STRUCT;

typedef struct my_struct {
SUB_STRUCT field1;
int field2;
int field3;
int field4;
} MY_STRUCT;

main() {

MY_STRUCT var =
{
.field1 = {
   .field1=1 ,
   .field3=3 },
.field2 = 2,
.field4 = 4
};
printf ("var.field1.field1 = %d\n", var.field1.field1);
printf ("var.field1.field2 = %d\n", var.field1.field2);
printf ("var.field1.field3 = %d\n", var.field1.field3);
printf ("var.field2 = %d\n", var.field2);
printf ("var.field3 = %d\n", var.field3);
printf ("var.field4 = %d\n", var.field4);
}

var.field1.field1 = 1
var.field1.field2 = 0
var.field1.field3 = 3
var.field2 = 2
var.field3 = 0
var.field4 = 4