【问题标题】:passing a pointer member in structure which is member of another structure to a function which accepts double pointer将结构中的指针成员作为另一个结构的成员传递给接受双指针的函数
【发布时间】:2017-01-17 05:45:41
【问题描述】:

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

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 上编写了它,因为放置实际代码会不必要地复杂化,因为我只是在寻找具体的解决方案。

【问题讨论】:

标签: c struct


【解决方案1】:

简答:

pass(&gir->elephant.count);

你需要将count的地址传入elephantgir

您的一行无法编译:

// 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,在stdint.h中不存在,必须使用uint32_t。 @chux 注意你没有使用正确的标志来打印uint32_t in printf(),你必须使用PRIu32

struct Animal {
    uint32_t *count; 
};

struct forest {
    struct Animal elephant;
};

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

你不应该cast return of malloc

【讨论】:

  • 谢谢,我是直接在so上写的,所以报错
  • 我发现自己在 UV-ing ptr = malloc(sizeof *ptr * n); 回答 - 就是这么简单。很好的答案。
  • 顺便说一句 printf("Count:%d\n",**count); 需要工作。符号和宽度问题。
  • @HimanshuSourav 您不应该通过编辑破坏我的答案的问题来解决您的问题。
  • @Stargateur 已恢复
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-04
  • 1970-01-01
  • 2010-11-23
  • 1970-01-01
相关资源
最近更新 更多