strcpy vs. strcat strncpy vs. strncat

strcpy 与 strcat是两个常用的字符串处理的函数,经常可以用来给一个空的字符串赋值。

example:

char a[]="abcd";
char b[5];
strcpy(b, "");
strncpy(b, a, 4);
printf("b:%s\n", b);

上面这段代码的输出结果为:abcd烫烫

为什么在abcd之后会出现乱码呢?

查了资料之后发现strcpy(strncpy)不会自动在字符串之后添加终止符。当把strncpy换成strncat之后,程序就能正常运行了,这是因为strncat会自动添加终止符,但是这要求b有足够的size来容纳该终止符。

附:

C plus plus 网站对strncpy的描述:

Copy characters from string
Copies the first num characters of source to destination. If the end of the source C string (which is signaled by a null-character) is found before num characters have been copied, destination is padded with zeros until a total ofnum characters have been written to it.

No null-character is implicitly appended at the end of destination if source is longer than num. Thus, in this case,destination shall not be considered a null terminated C string (reading it as such would overflow).

destination and source shall not overlap (see memmove for a safer alternative when overlapping).

C plus plus 网站对strncat的描述:

Append characters from string
Appends the first num characters of source to destination, plus a terminating null-character.

If the length of the C string in source is less than num, only the content up to the terminating null-character is copied.

 

 

 

转载于:https://www.cnblogs.com/denflyson/archive/2013/06/03/3115507.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值