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

前端 未结 3 897
离开以前
离开以前 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 10:49

    The student structure only holds pointers to char arrays. Now the actual space in memory for the strings is allocated in your for cycle an its lifetime is limited by the scope of the for cycle, accessing it afterwards is undefined behaviour. In your case the space where the strings are has not been reused and overridden yet, so coincidentally you are able to get the last value stored (cases like this can also raise segmentation fault).

    You should have a look on some basic tutorial about pointers and c memory model. Allocating the arrays in the struct is a good solution (nucleon's answer). Also the scanf function can overflow you should limit the number of retrieved characters to match the size of allocated array.

提交回复
热议问题