Now I create a double pointer to store some words get from a .txt
document (Since there is no string
in C language.). I tried to use fgets
and fscanf
. When I run fgets
and fscanf
for the first time, I can store pointers in double pointers. But when I run it for the second time, I find that the value of the first time is completely overwritten. This is a part of code.
char **out = (char **)malloc(3 * sizeof(char *));
FILE *dictionary = NULL;
dictionary = fopen(filename, "r");
char store[6];
fscanf(dictionary, "%s", store);
printf("%s\n", store);
store[5] = '\n';
out[0] = store;
strcpy(store, "");
fscanf(dictionary, "%s", store);
out[1] = store;
printf("%s\n", out[0]);
printf("%s\n", out[1]);
fclose(dictionary);
return out;
The content of txt file is
cigar
rebut
sissy
My expected result from the code above is
cigar
cigar
rebut
but the exact output from the code above is
cigar
rebut
rebut
I just tried to store their values one by one, but it seems to tamper with my previous values as well. I've replaced pointers with arrays, but this keeps showing up. What do I need to pay attention to? Or is there a better alternative?
CodePudding user response:
Here, you need to allocate memory again for every 1D character array out[0] = (char*)malloc(5 * sizeof(char));
and use strcpy
, so the below is the corrected code.
char **out = (char **)malloc(3 * sizeof(char *));
FILE *dictionary = NULL;
dictionary = fopen(filename, "r");
char store[6];
out[0] = (char*)malloc(5 * sizeof(char));
fscanf(dictionary, "%s", store);
printf("%s\n", store);
strcpy(out[0], store);
out[1] = (char*)malloc(5 * sizeof(char));
fscanf(dictionary, "%s", store);
strcpy(out[1], store);
printf("%s\n", out[0]);
printf("%s\n", out[1]);
fclose(dictionary);
return 0;