Reputation: 21
I have :
typedef struct a{
int var;
}aa;
typedef struct b{
aa *a;
}bb;
int main()
{
bb *b;
b->a->var;
return 0;
}
struct a
nested in b
.
How to initialize value for variable var
using 2
pointers like this:
b->a->var;
?
Upvotes: 0
Views: 173
Reputation: 3812
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
.
Upvotes: 0
Reputation: 75062
b
to a valid pointer.b->a
to a valid pointer.b->a->var
.#include <stdlib.h>
typedef struct a{
int var;
}aa;
typedef struct b{
aa *a;
}bb;
int main(void)
{
bb *b;
/* initialize b */
b = malloc(sizeof(*b));
if (b == NULL) return 1;
/* initialize b->a */
b->a = malloc(sizeof(*b->a));
if (b->a == NULL)
{
free(b);
return 1;
}
/* initialize b->a->var */
b->a->var = 42;
/* free what are allocated */
free(b->a);
free(b);
return 0;
}
Upvotes: 5