0

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; ?

H.S.
  • 11,654
  • 2
  • 15
  • 32
  • 2
    Struct a is not nested in b (i.e. a part of b), it is just pointed by some member of b (one of many pointer members, potentially). – CiaPan Aug 12 '21 at 15:03

2 Answers2

5
  1. Initialize b to a valid pointer.
  2. Initialize b->a to a valid pointer.
  3. Initialize 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;
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
0

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.

Yun
  • 3,056
  • 6
  • 9
  • 28
  • You don't need to cast the return value from `malloc`. See: https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – Tim Randall Aug 12 '21 at 15:32
  • @TimRandall Interesting, thanks! I've updated the code to the other variant of `sizeof`. There are arguments on both sides of the casting issue. For now I'm keeping the casts, as I find implicit casts a bigger evil than minor clutter/repetition. – Yun Aug 12 '21 at 15:54