Array of structs in c: giving all the strings same values (with the int it works well). What sould I do?

前端 未结 3 873
离开以前
离开以前 2021-01-21 10:09

When I run the program and give values to the id, name, surname it gives them all the value of the last student. For instance if the last students name is Anna then all the othe

3条回答
  •  春和景丽
    2021-01-21 11:01

    The issue is that the loop variables go out of scope after each iteration, and you're left with dangling pointers in the Student instances. What you're seeing is the result of undefined behavior.

    What's probably happening is that the same char array is being passed into every student instance. Then you modify the same char array, overwriting the previous values.

    You'll need to make copies of the strings. Remember to create a function like Student_free where you free the dynamically allocated copies.

    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;
    }
    

提交回复
热议问题