我正在尝试学习 C 编程,但是当我尝试将未初始化的结构指针传递给函数时,我陷入了困境。
这是我的结构:
typedef struct {
char name[30];
char surname[30];
char gender;
char DOB[10];
int waist;
int hip;
}healthcare_table;
我的主要内容
int main() {
healthcare_table *records;
int step = 1;
load_healthcare_table(records,&step);
return 0;
}
我的函数将打开文件,并根据文本文件中的行数,初始化指针,但我不能这样做。有什么建议吗?
更新: 我犯了这样的错误,我不知道出了什么问题。 错误消息为:ConsoleApplication1.exe 中的 0x00D7529C 处引发异常:0xC0000005:读取位置 0x0000004C 时发生访问冲突。
这是我更新的代码:
typedef struct {
char name[30];
char surname[30];
char gender;
char DOB[10];
int waist;
int hip;
}healthcare_table;
void load_healthcare_table(healthcare_table **t, int *step) {
int i;
FILE *infile;
infile = fopen("records.txt", "r");
if (infile == NULL)
printf("File not opened successfully");
else
printf("File opened successfully");
for (i = 0; fscanf(infile, "%s %s %c %s %d %d", *t[*step]->name, *t[*step]->surname, t[*step]->gender, *t[*step]->DOB, t[*step]->waist, t[*step]->hip) != EOF; i++) {
if (fgetc(infile) == '\n') {
*step++;
//*t = (healthcare_table*)realloc(*t, *step);
//fprintf(infile, "%s %s %c %s %d %d", *t[*step]->name, *t[*step]->surname, t[i]->gender, *t[*step]->DOB, t[*step]->waist, t[*step]->hip);
}
}
*t = (healthcare_table*)malloc((*step) * sizeof(healthcare_table));
for (i = 0; fscanf(infile, "%s %s %c %s %d %d", *t[i]->name, *t[i]->surname, t[i]->gender, *t[i]->DOB, t[i]->waist, t[i]->hip) != EOF; i++) {
if (fgetc(infile) == '\n')
fprintf(infile, "%s %s %c %s %d %d", *t[i]->name, *t[i]->surname, t[i]->gender, *t[i]->DOB, t[i]->waist, t[i]->hip);
}
}
void display_healthcare_table(healthcare_table *records) {
}
void search() {
}
void WHR_interpreter() {
}
int main() {
healthcare_table *records=NULL;
int step = 0;
load_healthcare_table(&records, &step);
return 0;
}
更新2: 我认为问题出在fscanf和fprintf上。如果我错了,我该如何解决这个问题?
最佳答案
如果您不想在主函数中分配指针,您有两种可能的解决方案:
解决方案1
不要将healthcare_table指针传递给load_healthcare_table()函数,而是从函数本身返回初始化的指针。大致如下:
int main() {
healthcare_table *records;
int step = 1;
records = load_healthcare_table(&step);
return 0;
}
在这种情况下,您的 load_healthcare_table() 函数将是:
healthcare_table* load_healthcare_table(int* step) {
healthcare_table *table;
table = (healthcare_table*)malloc(sizeof(healthcare_table));
// Fill table here
return table;
}
重要说明 在这种情况下,请确保您不要在 load_healthcare_table() 函数本地创建表。一旦函数返回,这就会破坏表,从而产生垃圾数据。函数永远不应该返回指向其本地数据的指针。所以下面的例子是错误:
healthcare_table* load_healthcare_table(int* step) {
healthcare_table table;
// Fill table here
return &table;
}
解决方案2
将指向healthcare_table的指针传递给函数load_healthcare_table()。它看起来像这样:
int main() {
healthcare_table *records;
int step = 1;
load_healthcare_table(&records,&step);
return 0;
}
在这种情况下,load_healthcare_table() 函数将是:
void load_healthcare_table(healthcare_table** t, int* step ) {
*t = (healthcare_table*)malloc(sizeof(healthcare_table));
// Fill table here
}
编辑
正如 Ajay Brahmakshatriya 所建议的:坚持局部变量的标准 C 概念,而不是使用堆栈术语。
关于c - 指向函数的结构体指针未初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44076193/