'Is there a way to store the value of a pointer but do not access the address?
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 fgetsand fscanffor 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?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
