【发布时间】:2011-09-25 15:04:41
【问题描述】:
我遇到了问题,或者我只是做错了,因为我是 C 和结构的新手。我想要一个这样的文本文件:
3
Trev,CS,3.5
Joe,ART,2.5
Bob,ESC,1.0
并在第一行读取学生人数,然后从那里收集学生信息并将它们放入一个名为 StudentData 的结构中:
typedef struct StudentData{
char* name;
char* major;
double gpa;
} Student;
我遇到的问题是在我看似将数据分配给单个结构之后,结构数据变得混乱。我已经准确地评论了正在发生的事情(或者至少我认为是)。希望阅读起来不会很痛苦。
main(){
int size, i;
char* line = malloc(100);
scanf("%d\n", &size);//get size
char* tok;
char* temp;
Student* array[size]; //initialize array of Student pointers
for(i = 0; i<size;i++){
array[i] = malloc(sizeof(Student));//allocate memory to Student pointed to by array[i]
array[i]->name = malloc(50); //allocate memory for Student's name
array[i]->major = malloc(30);//allocate memory for Student's major
}
for(i = 0; i<size;i++){
scanf("%s\n", line);//grab student info and put it in a string
tok = strtok(line, ","); //tokenize string, taking name first
array[i]->name = tok;//assign name to Student's name attribute
// printf("%s\n",array[i]->name);//prints correct value
line = strtok(NULL, ",");//tokenize
array[i]->major = line;//assign major to Student's major attribute
// printf("%s\n",array[i]->major);//prints correct value
temp = strtok(NULL, ",");//tokenize
array[i]->gpa = atof(temp);//assign gpa to Student's gpa attribute
// printf("%.2f\n\n",array[i]->gpa); //prints correct value
}
for(i=0;i<size;i++){ //this loop is where the data becomes jumbled
printf("%s\n",array[i]->name);
printf("%s\n",array[i]->major);
printf("%.2f\n\n",array[i]->gpa);
}
}
输出如下:
Trev
Joe
3.50
Joe
Bob
2.50
Bob
ESC
1.00
我无法真正理解在赋值和打印它们之间的内存中发生了什么。
【问题讨论】: