我有一个struct
定义为
typedef struct
{
char* name;
char* ID;
int marks;
char* details;
} Student;
另一个作为
typedef struct
{
int n;
Student* stud_array;
} Batch;
一个文件具有特定格式的不同批次学生的条目,我正在从该文件中读取以填充BatchArray
类型Batch*
填充每个字段后,我正在使用
puts(BatchArray[no_of_batches-1].stud_array[i].name);
puts(BatchArray[no_of_batches-1].stud_array[i].ID);
printf("%d\n",BatchArray[no_of_batches-1].stud_array[i].marks);
看看结果。它给了我正确的输出。
但是,一切都完成后,当我想遍历 时BatchArray
,只有marks
每个结构中的字段保留该值。和显示name
为ID
一些随机垃圾值。
迭代代码是标准的。尽管如此,它就在这里。
for(i = 0; i < no_of_batches; i++) {
currBSize = BatchArray[i].n;
printf("Batch %d\n", (i+1));
printf("Batch size %d\n", currBSize);
for(j = 0; j < currBSize; j++) {
puts(BatchArray[i].stud_array[j].name);
}
}
我正在处理的问题需要找到每批的平均分数,所以这不是问题。但我想知道为什么其他字段被重置为垃圾值。
有人可以帮忙吗?
编辑:这是我填充字段的方式。
该文件由这样的条目组成
3 名称1 ID1 标记1 名称2 ID2 标记2 名称3 ID3 标记3 2 名称4 ID4 标记4 名称5 ID5 标记5
这就是代码。
no_of_batches = 0;
infileptr = fopen (infilename, "r");
BatchArray = (Batch *) malloc(sizeof(no_of_batches));
int MAX_BUFF = 100;
char currLine[MAX_BUFF];
while (fgets(currLine, MAX_BUFF, infileptr) != NULL) {
no_of_batches++;
BatchArray = (Batch *) realloc(BatchArray, no_of_batches*sizeof(Batch));
currBatchSize = atoi(currLine);
BatchArray[no_of_batches-1].n = currBatchSize;
printf("currBatchSize : %d\n",BatchArray[no_of_batches-1].n);
BatchArray[no_of_batches-1].stud_array = (Student *) malloc(currBatchSize*sizeof(Student));
for(i = 0; i < currBatchSize; i++) {
fgets(currLine, MAX_BUFF, infileptr);
currLine[strlen(currLine)-1] = '\0';
BatchArray[no_of_batches-1].stud_array[i].details = currLine;
//getting the Name from currLine
j = 0;
len = strlen(currLine);
char buildName[len];
while(currLine[j] != ' ') {
buildName[j] = currLine[j];
j++;
}
buildName[j] = '\0';
BatchArray[no_of_batches-1].stud_array[i].name = buildName;
j++;
//getting the ID from currLine
k = 0;
char buildID[len];
while(currLine[j] != ' ') {
buildID[k] = currLine[j];
j++;
k++;
}
buildID[k] = '\0';
BatchArray[no_of_batches-1].stud_array[i].ID = buildID;
puts(BatchArray[no_of_batches-1].stud_array[i].name);
puts(BatchArray[no_of_batches-1].stud_array[i].ID);
//getting the marks from currLine
k = 0;
j++;
char buildMarks[len];
while(currLine[j] != '\0') {
buildMarks[k] = currLine[j];
j++;
k++;
}
buildMarks[k] = '\0';
BatchArray[no_of_batches-1].stud_array[i].marks = atoi(buildMarks);
printf("%d\n",BatchArray[no_of_batches-1].stud_array[i].marks);
}
puts("");
}