Reputation: 1916
I'm currently refreshing my C skills and having trouble with the following code:
int main (int argc, const char * argv[]) {
@autoreleasepool {
int numberOfTestCases;
scanf("%d", &numberOfTestCases);
char *a[numberOfTestCases];
for (int i = 0; i < numberOfTestCases; i++) {
char input[100];
scanf("%s", input);
a[i] = input;
}
for (int k = 0; k < numberOfTestCases; k++) {
printf("%s\n", a[k]);
}
}
return 0;
}
First I want to enter the user a number to determine how many strings she/he wants to enter.
Second I want to let the user enter the number of strings and store them in an array of strings.
Last I want to loop over that array and print out all the values. So my test input is e.g. something like:
5
My
name
is
John
Doe
with an expected result of
My
name
is
John
Doe
Instead the result is:
Doe
Doe
Doe
Doe
Doe
I can't figure out how to insert the input in the array.. very thankful for a hint in the right direction.
Upvotes: 0
Views: 122
Reputation: 409166
If that was a C program, you would have undefined behavior because you have an array of pointers, and each pointer you make point to a variable inside a nested scope, which means that variable will be out of scope outside of the loop, and the pointers (who are all pointing to the same memory) will be stray leading to said undefined behavior.
Upvotes: 3