fscanf 更改字符串变量?
fscanf changes string variable?
我是编程初学者,目前正在学习 C,但遇到了一些让我感到困惑的事情。
在我的 while 循环中我有:
char* bword = word
fscanf(fp, "%s", word);
其中 word 是一个 char[46],bword 是一个 char*,fp 是文件(在本例中是字典)。我想在扫描 fp 时在它被替换之前跟踪这个词。在我看来,在变量发生变化之前将其分配给变量似乎是合乎逻辑的。但是如果我在 fscanf(fp, '%s", word) 之后打印 bword 然后它就变成了新词!我真的不明白为什么以及如何。
如果我这样做:
bword = word;
printf("1.%s\n", word);
printf("2.%s\n", bword);
// scan the file for a for a word and store in word
fscanf(fp, "%s", word);
printf("3.%s\n", word);
printf("4.%s\n", bword);
我在命令行中得到这些结果:
1.
2.
3.a
4.a
(你看不到1和2之前的任何东西,因为当时这个词是空的)。
我还尝试在循环之前将单词分配给 "bar" 但后来我得到:
1.bar
2.bar
3.a
4.a
那我该如何解决呢?我不想改变 bword。
首先要了解指针(可以看tutorialspoint)。
然后你发现数组是一个指向内存的指针,所以当你分配它们时,你只是分配地址,所以如果其中一个改变,另一个也会改变。如果你想复制你不能分配的字符串,那么你必须复制它们,你可以使用 strcpy()
函数。正如手册页所说,它具有以下语法:
char *strcpy(char *dest, const char *src);
The strcpy() function copies the string pointed to by src, including the terminating null byte ('[=12=]'), to the buffer pointed to by dest. The strings may not overlap, and the destination string dest must be large enough to receive the copy. Beware of buffer overruns!
你需要明白这
char *bword = word;
声明了指向数组第一个元素的指针word
,这意味着修改bword
也会修改word
,因为bword
只是一个引用1 到真正的数据位置是数组 word
如果你想让 bword
和 word
相互独立,那么就把 bword
做成一个数组,这样它就可以存储在不同的位置,就像这样
char bword[SOME_REASONABLE_SIZE];
从这里您可以调用 fscanf()
并传递适当的数组,结果将是您之前预期的结果。
注意,当您将数组传递给 fscanf()
时,本质上您传递的是指向它的第一个元素的指针,这正是您的 bword
最初的位置。
1一般意义上的引用,不是c++意义上的。
我是编程初学者,目前正在学习 C,但遇到了一些让我感到困惑的事情。
在我的 while 循环中我有:
char* bword = word
fscanf(fp, "%s", word);
其中 word 是一个 char[46],bword 是一个 char*,fp 是文件(在本例中是字典)。我想在扫描 fp 时在它被替换之前跟踪这个词。在我看来,在变量发生变化之前将其分配给变量似乎是合乎逻辑的。但是如果我在 fscanf(fp, '%s", word) 之后打印 bword 然后它就变成了新词!我真的不明白为什么以及如何。
如果我这样做:
bword = word;
printf("1.%s\n", word);
printf("2.%s\n", bword);
// scan the file for a for a word and store in word
fscanf(fp, "%s", word);
printf("3.%s\n", word);
printf("4.%s\n", bword);
我在命令行中得到这些结果:
1.
2.
3.a
4.a
(你看不到1和2之前的任何东西,因为当时这个词是空的)。 我还尝试在循环之前将单词分配给 "bar" 但后来我得到:
1.bar
2.bar
3.a
4.a
那我该如何解决呢?我不想改变 bword。
首先要了解指针(可以看tutorialspoint)。
然后你发现数组是一个指向内存的指针,所以当你分配它们时,你只是分配地址,所以如果其中一个改变,另一个也会改变。如果你想复制你不能分配的字符串,那么你必须复制它们,你可以使用 strcpy()
函数。正如手册页所说,它具有以下语法:
char *strcpy(char *dest, const char *src);
The strcpy() function copies the string pointed to by src, including the terminating null byte ('[=12=]'), to the buffer pointed to by dest. The strings may not overlap, and the destination string dest must be large enough to receive the copy. Beware of buffer overruns!
你需要明白这
char *bword = word;
声明了指向数组第一个元素的指针word
,这意味着修改bword
也会修改word
,因为bword
只是一个引用1 到真正的数据位置是数组 word
如果你想让 bword
和 word
相互独立,那么就把 bword
做成一个数组,这样它就可以存储在不同的位置,就像这样
char bword[SOME_REASONABLE_SIZE];
从这里您可以调用 fscanf()
并传递适当的数组,结果将是您之前预期的结果。
注意,当您将数组传递给 fscanf()
时,本质上您传递的是指向它的第一个元素的指针,这正是您的 bword
最初的位置。
1一般意义上的引用,不是c++意义上的。