我的意圖是將source
字符串複製到dest
字符串。如果我編譯以下程序:Memset和字符
#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: error: lvalue required as increment operand
while (*dest) { printf("%c",*dest++); } ^
和
prog.c:11:38: error: lvalue required as increment operand
while (*dest) { printf("%c",*source++); } ^
爲什麼會出現這種情況?
第一個程序[不編譯](http://ideone.com/2Zy1hx)出於同樣的原因,第二個程序沒有。你確定這是你使用的來源嗎? – templatetypedef
另外,您不能將++應用於數組。 :-) – templatetypedef
相反,如果dest是一個數組,dest ++不是合法的C代碼。 – templatetypedef