博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
strcpy vs. strcat strncpy vs. strncat
阅读量:6913 次
发布时间:2019-06-27

本文共 1263 字,大约阅读时间需要 4 分钟。

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  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

你可能感兴趣的文章
GitHub发布2017年度开发者报告,用户达2400万
查看>>
Java EE供应商和伦敦Java用户组宣布新的MicroProfile
查看>>
Python中的集合类模块collections详解
查看>>
Chef在InSpec 2.0增强了云安全的自动化功能
查看>>
升级的Electric Cloud平台增添了大型机和微服务功能
查看>>
Java 虚拟机经典六问
查看>>
Dart 2为移动开发做出改进
查看>>
无服务器TOP3大关键问题及解决方案
查看>>
基于Gitflow分支模型自动化Java项目工作流
查看>>
全能App研发助手!滴滴开源DoraemonKit
查看>>
.NET开源简史
查看>>
Bustle的GraphQL实践
查看>>
Oracle推出轻量级Java微服务框架Helidon
查看>>
NoSQL 数据库敏捷数据模型
查看>>
Oracle回应用户锁定,自治数据库是更好选择
查看>>
函数式编程能否支持更高效的区块链基础设施?
查看>>
iOS 开发周报: 苹果回应微信关闭赞赏通知、iOS 静态库、动态库与 Framework 都是什么...
查看>>
苹果发布Core ML 2
查看>>
荷兰铁路在采纳敏捷和精益中的做法
查看>>
centos rocksdb 性能测试笔记(二)
查看>>