i'm learning c , i'm playing around structures, have found behaviour can't explain, , i'd know why happens.
this code:
struct my_struct{ char *name; }; int main() { struct my_struct arr[3]; int = 0; char str[10]; while (i<3) { fgets(str, 10, stdin); arr[i].name = str; printf("array number %d: %s", i, arr[i].name); i++; } printf("1 - %s\n2 - %s\n3 - %s", arr[0].name, arr[1].name, arr[2].name); return 0; }
my input :
test1 test2 test3
expected output :
array number 0: test1 array number 1: test2 array number 2: test3 1 - test1 2 - test2 3 - test3
resulting output:
array number 0: test1 array number 1: test2 array number 2: test3 1 - test3 2 - test3 3 - test3
resulting output:
the issue is, long while loop keeps running, seems alright; however, when exits, seems set each of "name" values of structs in array last one's.
if, once out of loop , before last printf(), set name of last struct in array manually, 1 updated, previous structs' names still set last 1 entered inside loop.
i imagine i'm missing sth memory management flushing buffer before calling fgets() again or sth, can't figure out happening. know about?
this expect, think way, have char str[10]
, memory in string stored. when set each of array names arr[i].name = str
pointing char * name
@ memory. here loop doing:
0. str = []; arr[0].name = null; arr[1].name = null; arr[1].name = null; 1. str = [string1]; arr[0].name = str; arr[1].name = null; arr[1].name = null; 2. str = [string2]; arr[0].name = str; arr[1].name = str; arr[1].name = null; 3. str = [string3]; arr[0].name = str; arr[1].name = str; arr[1].name = str;
so end of loop, of arr.name
pointers point @ string , have edited string each time. if want individual arr
elements store own string better off doing this:
struct my_struct{ char name[10]; // note how each instance of `my_struct` stores own string. }; int main() { struct my_struct arr[3]; int = 0; while (i<3) { fgets(arr[i].name, 10, stdin); printf("array number %d: %s", i, arr[i].name); i++; } printf("1 - %s\n2 - %s\n3 - %s", arr[0].name, arr[1].name, arr[2].name); return 0; }
as final note should avoid using fgets
(see here). prefer getline
instead.
Comments
Post a Comment