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

标签 c arrays string struct

当我运行程序并为 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/

相关文章:

我可以将 C 内联函数桥接到 Swift 吗?

c++ - 从 C++ 文件中读取的奇怪数组

java - 比较命令行参数引用返回 false 而字符串数组返回 true

c - 在 Linux 下,recv 是否可以在 UDP 上返回 0?

c - 如何从整数创建时间字符串

c++ - 使用变量初始化缓冲区数组的长度

php - 从数据库中检索数据并统计数据出现的次数

java - Axis 1.4 无法正确反序列化数组

C strcpy 和 char

java - 根据各个字段的长度拆分字符串