I'm trying to write a code for a function that takes an empty array of pointers and its length n. And scans n strings of max length of MAX_LEN (a defined constant) until a new line is given by the user. The strings are separated by one space.
int scan_strings(char * words[], int n) {
char current = getchar(); // to make sure that there is no new line
int i = 0, j = 0, on = 1;
while (scanf("%c",¤t) == 1 && (current != '\n' || on)) {
char str[MAX_LEN]; // a defined constant
on = 0;
if (current != ' ') {
str[i] = current;
i++;
}
else {
str[i] = 0;
i = 0;
*(words+j) = &str;
j++;
}
}
return 1;
}
For some reason, the array after writing "foxes are red" is just:
0x002b8f0c "red"
0x002b8f0c "red"
"ERROR READING CHARACTERS"
"ERROR READING CHARACTERS"
"ERROR READING CHARACTERS"
...
How can I fix this?