//----------------------------------------------------------------------------
#include <stdio.h>
#include <string.h>
int main()
{
char c1[10]="abcdef";
strcpy(c1+1,c1);
printf("%s/n",c1);
return 0;
}
運行結果:
aabcddf
解釋:
拷貝的時候是4個字節來處理的
第一組:abcd
檢查其中沒有0,於是把這四個字節一起拷貝到目標串中。
這時你的字符串變成了:aabcdf
src指向d,dest指向f
第二組:df/0
檢查到其中有零,並且是在第三個,於是把頭兩個字節寫入目標串的頭兩個字節,
字符串變成aabcddf
然後把後一個字節設成0。
這樣你就得到了字符串aabcddf
(1) a b c d e f _ _ _ _
a a b c d f _ _ _ _
(2) a a b c d f _ _ _ _
a a b c d d f
//-----------------------------------------------------------------------------
//----------------------------------------------------------------------------
同理解釋困惑我已久的問題
#include <stdio.h>
#include <string.h>
int main()
{
char a[]="Hello World!";
printf("a=%d/n",strlen(a));
printf(a);
printf("/n");
char b[1];
// memset(b,0,1);
printf("b=%d/n",strlen(b));//用錯
printf(b);
printf("/n");
strcpy(b,a);
printf(b);
printf("b=%d/n",strlen(b));
printf(a);
printf("a=%d/n",strlen(a));
return 0;
}
運行結果:
a=12
Hello World!
b=16
燙燙Hello World!
Hello World!b=12
o World!a=8
Press any key to continue
b分配的不足但並沒有出現運行錯誤?(b越界)
(1) 初始化情況
aà H e l l o W o r l d !
bà_ _ _ _H e l l o W o r l d !
(2)
aà H e l l o W o r l d !
bà H e l l H e l l o W o r l d !
(3)
aà H e l l o W o r l d !
bà H e l l o W o o W o r l d !
(4)
aà H e l l o W o r l d !
bà H e l l o W o r l d ! r l d !