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.
NSStringWithFormat, which is Objective-C, but your code or question body don't even seem relevant to the title.a[i] = input;will make each array element point to the samechar input[100];which also goes out of scope outside theforloop.