【发布时间】:2016-11-23 17:50:21
【问题描述】:
我的目标是将source 字符串复制到dest 字符串。如果我编译以下程序:
#include <stdio.h>
int main(void) {
char dest[6];
char source[6];
strcpy(dest,source);
while (*dest) { printf("%c",*dest++); }
while (*source) {printf("%c",*source++); }
return 0;
}
我收到运行时错误。我怀疑这是因为strcpy 从源复制到目标,直到遇到\0。但是,它没有遇到空字符并继续从缓冲区复制,直到发生运行时错误。为了解决这个问题,我修改了代码如下:
#include <stdio.h>
int main(void) {
char dest[6];
char source[6];
memset(dest, '\0', 6*sizeof(dest)); //trying to set dest to '/0'
strcpy(dest,source);
while (*dest) { printf("%c",*dest++); }
while (*source) {printf("%c",*source++); }
return 0;
}
我收到以下错误:
prog.c:11:38: 错误:需要左值作为增量操作数
while (*dest) { printf("%c",*dest++); } ^
和
prog.c:11:38: 错误:需要左值作为增量操作数
while (*dest) { printf("%c",*source++); } ^
为什么会这样?
【问题讨论】:
-
第一个程序 doesn't compile 与第二个程序没有相同的原因。你确定那是你使用的来源吗?
-
另外,您不能将 ++ 应用于数组。 :-)
-
如果
dest是一个数组,dest++不是合法的 C 代码。 -
"我的目标是将目标字符串复制到源字符串。"我猜你的意思正好相反。
-
这一行:
memset(dest, '\0', 6*sizeof(dest));正在设置 36 个字节。前 6 个字节之后的所有字节都超出了数组的末尾。这是未定义的行为,可能导致段错误事件。