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

1
  • 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). Commented Aug 12, 2021 at 15:03

2 Answers 2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

You don't need to cast the return value from malloc. See: stackoverflow.com/questions/605845/…
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.