我的目标是将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:错误:增量操作数所需的lvalue 而(*dest) { printf("%c",*dest++);}^
和
prog.c:11:38:错误:增量操作数所需的lvalue 而(*dest) { printf("%c",*source++);}^
这一切为什么要发生?
发布于 2016-11-23 18:01:01
首先,如果要使用标准的C函数strcpy将源数组复制到另一个字符数组中,则源数组将为零终止。所以,而不是这个说法
memset(dest, '\0', 6*sizeof(dest)); 你至少应该写
memset(source, '\0', 6*sizeof(source));
^^^^^^ ^^^^^^^但是,即使这个语句也是错误的,因为它覆盖了分配给数组的内存。sizeof( source )已经等于6个字节,因为它来自数组声明
char source[6];因此,你必须写
memset(source, '\0', sizeof(source));
^^^^^^^^^^^^^事实上,有足够的时间来编写这样的
char source[6] = { '\0' };或者像这样
char source[6] = "";或者像这样
char source[6];
source[0] = '\0';数组是不可修改的lvalue。因此,您可能不会以以下方式编写
while (*dest) { printf("%c",*dest++); }而不是这句话,你可以写
for ( char *p = dest; *p; ++p ) { printf("%c", *p); }考虑到什么都不会输出,因为数组包含一个空字符串。您可以使用一些非空字符串文字初始化源数组。
发布于 2016-11-24 14:31:18
下面的代码干净地编译,并执行所需的操作。
已发布的代码与此代码之间的差异被注释了。
#include <stdio.h> // printf()
#include <string.h> // strcpy()
int main(void)
{
char dest[6]; // declared, containing garbage
char source[6] = "12345"; // declared, containing the string "12345\0"
strcpy(dest,source);
// now both arrays contain the string "12345\0"
// best to use a 'for()' statement for indexing through an array
for( size_t i=0; dest[i]; i++ ) { printf("%c", dest[i]); }
printf( "\n" ); // output the buffered data to the terminal
for( size_t i=0; source[i]; i++ ) { printf("%c", source[i]);}
printf( "\n" ); // output the buffered data to the terminal
// note, the following lines contain a precedence problem in
// the increment expressions and
// the address of an array declaration cannot be incremented
//while (*dest) { printf("%c",*dest++); }
//while (*source) {printf("%c",*source++); }
//return 0;// with modern C compilers,
// this line is not necessary in a 'main()' function
// when returning 0
} // end function: main发布于 2016-11-23 18:00:21
strcpy不是一个安全的函数,更喜欢使用strncpy。
错误是由于您试图增加数组,这是一个rvalue (即一个常量,您不能将它放在符号=的左边)。
迭代数组的常见方法是使用如下指针:
char *p = dest;
while (*p) { printf("%c",*p++); }https://stackoverflow.com/questions/40771189
复制相似问题