0

I have to pass a double pointer to a function

struct Animal{
        uint_32 *count; 
}


struct forest{
      struct Animal elephant;
}

void pass(uint32 **count){
       printf("Count:%d\n",**count);
}

int main(){
   struct  forest *gir;
   gir=(struct forest*)malloc(sizeof(struct forest));
   gir.elephant.count=(int*)malloc(sizeof(uint32_t));

   pass(_______); //have to pass count value
       return 0;
}

I have tried various combos but not sure how to handle this case.


kindly note, I have directly written it on SO, as putting up actual code would be unnecessarily complicating, as I am only looking for specific solution.

Himanshu Sourav
  • 700
  • 1
  • 10
  • 35

1 Answers1

4

Short answer:

pass(&gir->elephant.count);

You need to pass the address of count in elephant in gir.

One of your line can't compile:

// gir.elephant.count=(int *)malloc(sizeof(uint32_t)); this one
gir->elephant.count = malloc(sizeof *gir->elephant.count);
if (gir->elephant.count == NULL) { // you should always check the return of malloc
    free(gir);
    return 1;
}
gir->elephant.count = 42; // maybe you want affect count to something?

Plus you forget ; at the end of your structure declaration. And uint_32, don't exist in stdint.h, you must use uint32_t. @chux notice that you don't use the correct flag to print a uint32_t in printf(), you must use PRIu32.

struct Animal {
    uint32_t *count; 
};

struct forest {
    struct Animal elephant;
};

void pass(uint32_t **count)
   printf("Count:%" PRIu32 "\n", **count);
}

You shoud not cast return of malloc

Community
  • 1
  • 1
Stargateur
  • 24,473
  • 8
  • 65
  • 91