gpt4 book ai didi

c - c 中的结构数组 : giving all the strings same values (with the int it works well). 我该怎么办?

转载 作者:太空狗 更新时间:2023-10-29 15:54:13 24 4
gpt4 key购买 nike

当我运行程序并为 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 的结果.

可能发生的情况是相同的字符数组被传递到每个学生实例中。然后修改相同的 char 数组,覆盖以前的值。

您需要复制字符串。请记住创建一个类似 Student_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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com