现在的位置: 首页 > 综合 > 正文

strcpy的疑问

2013年06月28日 ⁄ 综合 ⁄ 共 1371字 ⁄ 字号 评论关闭
//-----------------------------------------------------------------------------

//----------------------------------------------------------------------------

#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
指向ddest指向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 !

抱歉!评论已关闭.