I'm working on an assignment in which I'm required to have a method return a pointer to an array of strings, read from a file. The function works, but when I try to assign the returned pointer to a variable in the main function, I end up with an array of null values. Here's my code:
#include <stdio.h>
char **buildAnsArray(){
FILE *in;
int num, i;
in = fopen("data.txt", "r");
fscanf(in, "%d", &num);
char ansArray[10][num];
for(i = 0; i < num; i++){
fscanf(in, "%s", ansArray[i]);
}
return ansArray;
};
main(){
char **ansArray = buildAnsArray();
}
The input file (data.txt) that I'm working with begins with:
3
B
20
1101
ansArray (in buildAnsArray) correctly contains {'B', '20', '1101'}, but ansArray (in main) is empty. I know I could just move everything to main and not worry about returning the pointer to the string array, but the assignment requires the buildAnsArray function. What can I do to fix this?
malloc). Right now you are creating your array on the stack, which means it can (and will) get cleaned up eventually after your function callchar**is not the same aschar[][N]). If your compiler didn't warn you about either, you need to turn up your warning levels to be considerably more verbose.