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