Strcpy和Strncpy的区别

(1)

char* p="how are you ?";
char name[20]="ABCDEFGHIJKLMNOPQRS";


strcpy(name,p);//name改变为"how are you ? OPQRS " ====>错误!

cout << name << endl;
strncpy(name,p,sizeof(name));   //name改变为"how are you ? " ====>正确!

cout << name << endl;

 

虽然同样输出how are you ?但strcpy后数组name中的内容:

-  name 0x0012ff40 "how are you ?" char [20]
  [0x0] 0x68 'h' char
  [0x1] 0x6f 'o' char
  [0x2] 0x77 'w' char
  [0x3] 0x20 ' ' char
  [0x4] 0x61 'a' char
  [0x5] 0x72 'r' char
  [0x6] 0x65 'e' char
  [0x7] 0x20 ' ' char
  [0x8] 0x79 'y' char
  [0x9] 0x6f 'o' char
  [0xa] 0x75 'u' char
  [0xb] 0x20 ' ' char
  [0xc] 0x3f '?' char
  [0xd] 0x00 char
  [0xe] 0x4f 'O' char
  [0xf] 0x50 'P' char
  [0x10] 0x51 'Q' char
  [0x11] 0x52 'R' char
  [0x12] 0x53 'S' char
  [0x13] 0x00 char
strncpy后数组name中的内容:

-  name 0x0012ff40 "how are you ?" char [20]
  [0x0] 0x68 'h' char
  [0x1] 0x6f 'o' char
  [0x2] 0x77 'w' char
  [0x3] 0x20 ' ' char
  [0x4] 0x61 'a' char
  [0x5] 0x72 'r' char
  [0x6] 0x65 'e' char
  [0x7] 0x20 ' ' char
  [0x8] 0x79 'y' char
  [0x9] 0x6f 'o' char
  [0xa] 0x75 'u' char
  [0xb] 0x20 ' ' char
  [0xc] 0x3f '?' char
  [0xd] 0x00 char
  [0xe] 0x00 char
  [0xf] 0x00 char
  [0x10] 0x00 char
  [0x11] 0x00 char
  [0x12] 0x00 char
  [0x13] 0x00 char

 

 

(2)
char* p="how are you ?";
char name[20];

strcpy(name,p); //name改变为"how are you ? 未知字符 " ====>错误!
name[sizeof(name)-1]='/0' //可不要

strncpy(name,p,sizeof(name)); //name改变为"how are you ? " ====>正确!

strcpy后数组name中的内容:

-  name 0x0012ff24 "how are you ?" char [20]
  [0x0] 0x68 'h' char
  [0x1] 0x6f 'o' char
  [0x2] 0x77 'w' char
  [0x3] 0x20 ' ' char
  [0x4] 0x61 'a' char
  [0x5] 0x72 'r' char
  [0x6] 0x65 'e' char
  [0x7] 0x20 ' ' char
  [0x8] 0x79 'y' char
  [0x9] 0x6f 'o' char
  [0xa] 0x75 'u' char
  [0xb] 0x20 ' ' char
  [0xc] 0x3f '?' char
  [0xd] 0x00 char
  [0xe] 0xcc char
  [0xf] 0xcc char
  [0x10] 0xcc char
  [0x11] 0xcc char
  [0x12] 0xcc char
  [0x13] 0xcc char

strncpy后数组name中的内容:
-  name 0x0012ff24 "how are you ?" char [20]
  [0x0] 0x68 'h' char
  [0x1] 0x6f 'o' char
  [0x2] 0x77 'w' char
  [0x3] 0x20 ' ' char
  [0x4] 0x61 'a' char
  [0x5] 0x72 'r' char
  [0x6] 0x65 'e' char
  [0x7] 0x20 ' ' char
  [0x8] 0x79 'y' char
  [0x9] 0x6f 'o' char
  [0xa] 0x75 'u' char
  [0xb] 0x20 ' ' char
  [0xc] 0x3f '?' char
  [0xd] 0x00 char
  [0xe] 0x00 char
  [0xf] 0x00 char
  [0x10] 0x00 char
  [0x11] 0x00 char
  [0x12] 0x00 char
  [0x13] 0x00 char


(3)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值