C 结构指针数组和分配结构数据

C 结构指针数组和分配结构数据,c,pointers,struct,C,Pointers,Struct,我遇到了一个问题,或者可能我只是做错了什么,因为我是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; 我遇到的问题是,在我似乎将数据分配给单个结构之后,结

我遇到了一个问题,或者可能我只是做错了什么,因为我是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);
  }
}
我真的无法理解在赋值和打印之间内存中发生了什么。如果有人能指导我解决这个问题,我将不胜感激


谢谢

你不能像那样对char*使用常规赋值。您将需要使用strcpy。例如:

strcpy(array[i]->name,tok);

否则,您将使所有数组[i]->name指向同一个字符串。

如何将该字符串处理为双精度?
strcpy(array[i]->name,tok);