Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 如何修改void函数中指向结构的指针_C_Pointers_Struct - Fatal编程技术网

C 如何修改void函数中指向结构的指针

C 如何修改void函数中指向结构的指针,c,pointers,struct,C,Pointers,Struct,我曾多次尝试用谷歌搜索我的问题,但从未找到适合我问题的答案。我必须修改指向函数内部结构的指针(用数据填充),然后将该指针用作其他函数的参数。 我有一个文本文件,其中有多个报告,我应该计算这些报告并将所有数据填充到指向结构的指针。这不是一个问题,我分配内存没有问题,通过文件没有问题,也填补了指针。但我不知道如何在函数外使用填充指针 struct report{ char name[50]; int id_number; } void function1(struct report **p

我曾多次尝试用谷歌搜索我的问题,但从未找到适合我问题的答案。我必须修改指向函数内部结构的指针(用数据填充),然后将该指针用作其他函数的参数。 我有一个文本文件,其中有多个报告,我应该计算这些报告并将所有数据填充到指向结构的指针。这不是一个问题,我分配内存没有问题,通过文件没有问题,也填补了指针。但我不知道如何在函数外使用填充指针

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;
}
#包括
#包括
结构报告{
字符名[50];
国际身份证号码;
};
void foo(结构报告**ptr){
*ptr=malloc(sizeof(struct report));//分配内存
(*ptr)->id_number=42;//填充分配的内存
}
int main(){
结构报告*指针;
foo(&pointer);//重要部分-传递到指向指针的foo()指针。
printf(“%d\n”,指针->标识号);
释放(指针);//不要忘记释放内存。
返回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;
}
#包括
#包括
结构报告{
字符名[50];
国际身份证号码;
};
void foo(结构报告**ptr){
*ptr=malloc(sizeof(struct report));//分配内存
(*ptr)->id_number=42;//填充分配的内存
}
int main(){
结构报告*指针;
foo(&pointer);//重要部分-传递到指向指针的foo()指针。
printf(“%d\n”,指针->标识号);
释放(指针);//不要忘记释放内存。
返回0;
}

是否在堆上的函数1中分配内存?是否在堆上的函数1中分配内存?