An array of strings is created in main and passed to a function. This function reads strings from a file and stores every line of the file in a different row of the array. Then finishes and returns to main. If I printf the contents of array[i] within the function, the text displayed in the screen is OK. If I do the same after returning to main(), printf writes only garbage. Why is main() not accessing the contents of the memory positions of the array?
void createlist(char* file, char **mylist) {
FILE* stream;
char name[40];
int i = 0;
stream = fopen(file, "r");
while (fgets(name, sizeof(name), stream) != NULL) {
mylist[i] = name;
printf(mylist[i]); // <------------------------This works OK!
i++;
}
fclose(stream);
}
void main(int argc, char* argv[]) {
char list[3000][40];
int i = 0;
resetchararray(list, 3000);
createlist("file", list);
for (i = 0; i < 3000; i++) {
printf(list[i]); // <---------------------This writes garbage
}
}
name
is a local variable in your function. It disappears after the function ends and leaves only garbage behind. To achieve what you are trying, use strcpy()
, instead of mylist[i] = name;
.
What is happening currently:
createlist("file", list);
pass list
by value @Shark warns!mylist[i] = name;
makes mylist[i]
hold the address of a local variable!createlist()
terminates, having changed only a local copy of list
(see point 1)