I'm learning C and i'm playing around with structures, but i have found some behaviour i can't explain, and i'd like to know why it happens.
This is my code:
struct my_struct{
char *name;
};
int main()
{
struct my_struct arr[3];
int i = 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, as long as the while loop keeps running, it seems to be alright; however, when it exits, it seems to set each of the "name" values of the structs in the array to the last one's.
If, once out of the loop and before the last printf(), I set the name of the last struct in the array manually, that is the only one which is updated, but the previous structs' names are still set to the last one entered inside the loop.
I imagine i'm missing sth about memory management like flushing the buffer before calling to fgets() again or sth, but can't figure out what is happening. Does anyone know what this is about?