将结构中的指针成员传递给另一个结构的成员到接受双指针的函数

时间:2017-01-17 05:45:42

标签: c struct

我必须将双指针传递给函数

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

我尝试了各种组合,但不知道如何处理这种情况。

请注意,我已将其直接写在SO上,因为放置实际代码会不必要地复杂化,因为我只是在寻找特定的解决方案。

1 个答案:

答案 0 :(得分:4)

简短回答:

pass(&gir->elephant.count);

您需要在count的{​​{1}}中传递elephant的地址。

你的一行无法编译:

gir

另外,在结构声明结束时忘记了// 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? 。并且;uint_32不存在,您必须使用uint32_t。 @chux注意到您没有使用正确的标记在uint32_t中打印printf(),您必须使用stdint.h

struct Animal {
    uint32_t *count; 
};

struct forest {
    struct Animal elephant;
};

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

你不应该PRIu32

相关问题