First of all, neither part of my code achieves what I desire. Secondly, I get different output when I use a function with the same piece of code. The goal is to enter multiple separate strings, save each as a following element of an array, and then print each element. Yet for the code included in main()
I receive six times the last string entered:
This one runs in main:
Enter 6 strings to be printed:
1
2
3
4
5
6
Printing input:
6
6
6
6
6
6
and when the exact same piece of instructions is summoned in a function I'm getting empty strings (6 times the "new tab" in a console):
This one is exactly the same & runs in external function:
Enter 6 strings to be printed:
1
2
3
4
5
6
Printing input:
Now I do know that variables in a function exist only in the scope of this function, but still I do not understand this behavior. What should I do to achieve this effect using arrays, both to work in a function and in main?
#include <stdio.h>
#include <stdlib.h>
void printStrings (void) {
printf("Enter 6 strings to be printed:\n");
char *tmp_ans[6];
char *tmp;
for (int j = 0; j < 6; j++) {
tmp_ans[j] = gets(tmp);
}
printf("Printing input:\n");
for (int i = 0; i < 6; i++) {
printf("%s\n", tmp_ans[i]);
}
}
int main() {
printf("This one runs in main:\n\n");
printf("Enter 6 strings to be printed:\n");
char *tmp_ans[6];
char *tmp;
for (int j = 0; j < 6; j++) {
tmp_ans[j] = gets(tmp);
}
printf("Printing input:\n");
for (int i = 0; i < 6; i++) {
printf("%s\n", tmp_ans[i]);
}
printf("This one is exactly the same & runs in external function:\n\n");
printStrings();
return (EXIT_SUCCESS);
}
I know that gets()
is bad/evil/etc, but for my own purpose it is just enough and I use it because it's simple.