Struct a
is not nested in struct b
, but struct b
contains a pointer to a a struct a object.
The two objects' pointers can be initialized independently E.g.: First allocate memory for a
, then allocate memory for b
, and finally assign the memory allocated for a
to b->a
.
However, it would be better to allocate memory for b
first:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int var;
} aa;
typedef struct {
aa *a;
} bb;
int main() {
bb *b = (bb*) malloc(sizeof *b);
b->a = (aa*) malloc(sizeof *(b->a));
b->a->var = 5;
printf("%d\n", b->a->var);
free(b->a);
free(b);
}
(Checking malloc
's return values omitted for brevity.)
Note the free'ing of memory in the reverse order. If b
would have been free'd first, the pointer to a
would have been lost.
Also, note how the typedef's do not declare an additional unused struct a
and struct b
.