【发布时间】:2017-10-19 22:43:12
【问题描述】:
我正在尝试学习 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。如果我错了,我该如何解决?
【问题讨论】:
-
开始正确地格式化这个烂摊子和minimal reproducible example。
-
C 允许使用野指针,这是语言的一个缺陷。确保所有指针都为空或指向内存中的有效对象。
标签: c arrays pointers data-structures structure