有没有办法存储指针的值但不访问地址?
Is there a way to store the value of a pointer but do not access the address?
现在我创建一个双指针来存储从.txt
文档中获取的一些单词(因为C语言中没有string
。)。我尝试使用 fgets
和 fscanf
。当我第一次运行fgets
和fscanf
时,我可以用双指针存储指针。但是当我第二次运行的时候,发现第一次的值被完全覆盖了。这是代码的一部分。
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;
txt文件内容为
cigar
rebut
sissy
我对上述代码的预期结果是
cigar
cigar
rebut
但上面代码的确切输出是
cigar
rebut
rebut
我只是试图将它们的值一一存储,但它似乎也篡改了我以前的值。我已经用数组替换了指针,但这一直出现。我需要注意什么?或者有更好的选择吗?
这里需要为每个一维字符数组out[0] = (char*)malloc(5 * sizeof(char));
重新分配内存,并使用strcpy
,所以下面是修改后的代码
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;
现在我创建一个双指针来存储从.txt
文档中获取的一些单词(因为C语言中没有string
。)。我尝试使用 fgets
和 fscanf
。当我第一次运行fgets
和fscanf
时,我可以用双指针存储指针。但是当我第二次运行的时候,发现第一次的值被完全覆盖了。这是代码的一部分。
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;
txt文件内容为
cigar
rebut
sissy
我对上述代码的预期结果是
cigar
cigar
rebut
但上面代码的确切输出是
cigar
rebut
rebut
我只是试图将它们的值一一存储,但它似乎也篡改了我以前的值。我已经用数组替换了指针,但这一直出现。我需要注意什么?或者有更好的选择吗?
这里需要为每个一维字符数组out[0] = (char*)malloc(5 * sizeof(char));
重新分配内存,并使用strcpy
,所以下面是修改后的代码
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;