当我运行程序并为 id、name、surname 赋值时,它为它们提供了最后一个学生的所有值。例如,如果最后一个学生的名字是 Anna,那么数组的所有其他名字都是 Anna。随着成绩它运作良好!我试过没有“构造函数”功能,但发生了同样的事情。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Student{ /*struct for student info*/
char *id;
char *name;
char *surname;
int grade;
};
struct Student* Student_new(char* id, char* name, char* surname, int grade);
/*fuction: Student 'constructor'*/
int main(int argc, char *argv[]) {
int no; /*number of students*/
printf("Welcome! \n\nNumber of students: ");
scanf("%d", &no);
struct Student *studentArray[no]; /*arary of struct students*/
int i; /*counter*/
for(i=0; i<no; i++){
char id[10], name[10], surname[10];
int grade;
printf("\n\nStudent(%d)\n", i+1);
printf("id: ");
scanf("%s", id);
printf("name: ");
scanf("%s", name);
printf("surname: ");
scanf("%s", surname);
printf("grade: ");
scanf("%d", &grade);
studentArray[i] = Student_new(id, name, surname, grade); /*using Student
'constructor' to initialize the array*/
}
for(i=0; i<no; i++){
printf("%s %s %s %d \n", studentArray[i]->id, studentArray[i]-
>name, studentArray[i]->surname, studentArray[i]->grade);
}
return 0;
}
struct Student* Student_new(char* id, char* name, char* surname, int grade)
{
struct Student* st = malloc(sizeof(struct Student));
st->id = id;
st->name = name;
st->surname = surname;
st->grade = grade;
return st;
}
请帮忙!!
最佳答案
问题是每次迭代后循环变量都会超出范围,并且在 Student
实例中留下悬空指针。你看到的是 undefined behavior 的结果。
可能发生的情况是相同的字符数组被传递到每个学生实例中。然后修改相同的字符数组,覆盖以前的值。
您需要制作字符串的副本。记得创建一个像 Student_free
这样的函数,你可以在其中对动态分配的副本进行 free
。
struct Student* Student_new(char* id, char* name, char* surname, int grade)
{
struct Student* st = malloc(sizeof(struct Student));
st->id = strndup(id, 10);
st->name = strndup(name, 10);
st->surname = strndup(surname, 10);
st->grade = grade;
return st;
}
关于c - c : giving all the strings same values (with the int it works well). 中的结构数组我该怎么办?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44203493/