I'm trying to create a pointer array that holds strings of various sizes. I want to prompt the user for input, store the values in the array, and then print them using the following code:
#include <stdio.h>
int main() {
char *string_array[10];
for (int x = 0; x < 2; x++)
{
char string[50];
printf("Input Name of Fruit number %d\n", x);
fgets(string, 50, stdin);
string_array[x] = string;
}
for (int x = 0; x < 2; x++)
{
printf("%s\n", string_array[x]);
}
return 0;
}
I expected this code to take in two user prompts and store the address of each string. However, when I run the code, the final user prompt represents the value stored at each address in the pointer array. On inspection, I found that every address is the same.
I presume this is because the string
variable is instantiated to the same address every time, or is never changed despite being defined in each for loop. What's happening here with the addresses to prevent this code from working?