Thanh Huy Vu
Thanh Huy Vu

Reputation: 21

Pointer to pointer to variable of struct in C

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

Answers (2)

Yun
Yun

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

MikeCAT
MikeCAT

Reputation: 75062

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

Upvotes: 5

Related Questions