栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C语言-str家族之strcat,strncat

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C语言-str家族之strcat,strncat

文章目录
  • 一、strcat
  • 二、strncat

一、strcat

声明:char *strcat(char *dest, const char *src)
作用:在dest后面追加src,你可以简单的的认为这是个连接符
源码:

#undef strcat
char *strcat(char *dest, const char *src)
{
	char *tmp = dest;

	while (*dest)
		dest++;
	while ((*dest++ = *src++) != '')
		;
	return tmp;
}

说明:dest自增到结束符,然后执行(*dest++ = *src++) != ''进行追加
示例:

#include 
#include 
 
int main()
{
	char src[10] = "DEF";
	char dest[10] = "ABC";

	printf("strlen(dest): %ldn", strlen(dest));

	strcat(dest,src);
	
	printf("strlen(dest): %ldn", strlen(dest));
	printf("dest: %sn", dest);
	
	return 0;
}

过程:“ABC”—>“ABCDEF”

strlen(dest): 3
strlen(dest): 6
dest: ABCDEF

man手册中的描述:从dest的结束符开始追加(覆盖了结束符),追加完后会在最后加上一个结束符。还有就是dest空间要足够大,不能溢出

DESCRIPTION
       The  strcat()  function  appends  the src string to the dest string, overwriting the
       terminating null byte ('') at the end of dest, and then adds  a  terminating  null
       byte.   The  strings may not overlap, and the dest string must have enough space for
       the result.  If dest is not large enough, program behavior is unpredictable;  buffer
       overruns are a favorite avenue for attacking secure programs.
二、strncat

了解了strcat,strncat的功能一看便知,追加src的前n个bytes

char *strncat(char *dest, const char *src, size_t count)
{
	char *tmp = dest;

	if (count) {
		while (*dest)
			dest++;
		while ((*dest++ = *src++) != 0) {
			if (--count == 0) {
				*dest = '';
				break;
			}
		}
	}
	return tmp;
}

说明:执行(*dest++ = *src++) != 0)后,执行--count,count == 0时,在dest当前位置加结束符 ‘’
示例:把上面示例代码strcat(dest,src);改成strncat(dest,src,2);得到如下结果

strlen(dest): 3
strlen(dest): 5
dest: ABCDE

如果有对以下字符数组初始化有疑问的,可以参考这篇文章

char arr[] = "ABC"; 
char arr[] = {"ABC"}; 
char *a = "ABC";
char *a; a = "ABC";
char arr[]; arr[] = "ABC";	//错误用法

注意:使用这类函数时一定要注意,不要越界!不要越界!不要越界!使用前确认dest空间足够存放src的追加。因为这类函数不检查边界问题,C语言对越界也不报错。

本人新手一粒,如有错误欢迎指出!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1009788.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号