我有一个 struct
定义为
typedef struct
{
char* name;
char* ID;
int marks;
char* details;
} Student;
还有一个
typedef struct
{
int n;
Student* stud_array;
} Batch;
一个文件包含特定格式的不同批处理学生的条目,我正在从该文件中读取以填充 Batch*
类型的 BatchArray
填充每个字段后我正在使用
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("");
}
最佳答案
代替
BatchArray[no_of_batches-1].stud_array[i].name = buildName;
写
BatchArray[no_of_batches-1].stud_array[i].name = strdup(buildName);
第一种情况的问题是name
指向buildName
,它是一个栈上的数组,每当栈内容改变时就会被覆盖。
在第二种情况下,您已将数组复制到新分配的堆内存(与 malloc
或 realloc
一样),它将保持不变,直到您 free
它。
关于c - 访问结构中的字符指针字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11773683/