c - 如何修改指向void函数内部结构的指针

标签 c pointers struct

我多次尝试用谷歌搜索我的问题,但从未找到适合我问题的答案。我必须修改指向函数内部结构的指针(用数据填充它),然后将该指针用作另一个函数的参数。 我有一个包含多个报告的文本文件,我应该对报告进行计数并将所有数据填充到指向结构的指针。这不是问题,我毫无问题地分配了内存,毫无问题地通过了文件,还填充了指针。但是我不知道如何在函数外部使用填充指针。

struct report{
  char name[50];
  int id_number;
}

void function1(struct report **ptr){
  //do stuff like count the number of reports in file
  //and allocate memmory for pointer to structure
  //and fill the pointer to structure with data
}
int main() {
  struct report *pointer;
  function(pointer);
  //now I expect variable 'pointer' to be filled and ready to use by another functions
  return 0;
}

能否请您提出一些解决方案?感谢您的宝贵时间和帮助。

最佳答案

请看例子:

#include <stdlib.h>
#include <stdio.h>

struct report{
  char name[50];
  int id_number;
};

void foo(struct report **ptr){
  *ptr = malloc(sizeof(struct report));  // allocate memory
  (*ptr)->id_number = 42;  // fill the allocated memory
}

int main() {
  struct report *pointer;
  foo(&pointer);  // important part - pass to the foo() pointer to the pointer.

  printf("%d\n", pointer->id_number);

  free(pointer);  // do not forget to free the memory.
  return 0;
}

关于c - 如何修改指向void函数内部结构的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53042378/

相关文章:

c - 我是否错误地使用了 scanf?

c - 在 C 中读取结构(结构信息)

c - : do in a struct declaration after a member 是什么

delphi - 为什么在调用 Dispose 之前必须转换为特定的指针类型?

c - 结构实现建议

arrays - 生成伪语言的 C 程序 - 全局 3D 数组太大(段错误)?

c - 以下 memcpy 如何超出 C 中的数组?

c - 查找所有字符串中存在的共同字符

objective-c - 将 C 指针添加到 NSMutableArray

C++ 不允许指向不完整类类型的指针