【C语法学习】25 - strcat()函数

1 函数原型

strcat():将src指向的字符串附加在dest指向的字符串末尾,将两个字符串拼接成一个字符串,函数原型如下:

char *strcat(char *dest, const char *src);

2 参数

strcat()函数有两个参数src和dest:

  1. 参数src是指向源字符串的指针,类型为char*型;
  2. 参数dest是指向目的字符串的指针,类型为char*型。

3 返回值

strcat()函数的返回值类型为char*型,返回值为dest。

4 使用说明

  1. strcat()函数将src指向的字符串附加在dest指向的字符串末尾,这里的"附加"可以理解为拷贝,即将src指向的字符串拷贝至dest指向的字符串末尾;但是,这里的"拷贝"是一种不完全拷贝,只拷贝字符串末尾的空字符’\0’之前的字符,很多博文说连同末尾的空字符’\0’一起拷贝是不正确的,可以比较C语言标准关于strcpy()函数和strcat()函数描述的差异;
  2. strcat()函数在拼接两个字符串时,用src指向的字符串的第一个字符src[0]覆盖dest指向的字符串末尾的空字符’\0’;
  3. strcat()函数在拼接两个字符串后,在拼接后的字符串末尾添加空字符’\0’;
  4. strcat()函数不检查dest指向的内存空间的大小,必须保证dest所指向的内存空间足够大,能够容纳下src指向的字符串和dest指向的字符串,否则会导致溢出。

C语言标准描述如下:

1. Appends a copy of the null-terminated byte string pointed to by src to the end of the null-terminated byte string pointed to by dest. 
2. The character src[0] replaces the null terminator at the end of dest. 
3. The resulting byte string is null-terminated.
4. The behavior is undefined if the destination array is not large enough for the contents of both src and dest and the terminating null character. 
5. The behavior is undefined if the strings overlap. 
6. The behavior is undefined if either dest or src is not a pointer to a null-terminated byte string.

5 示例

5.1 示例1

代码如下所示:

int main()
{
   char dest[25];
   char src[] = "Hello World";

   int i = 0;
   for (i = 0; i < 25; i++)
   {
      if (i == 0)
         dest[i] = '\0';
      else
         dest[i] = 'a';
   }

   strcat(dest, src);
   strcat(dest, "\n");
   strcat(dest, "I Love You");

   puts(dest);

   return 0;
}

代码运行结果如下图所示:

在这里插入图片描述

代码及运行结果分析如下:

  1. dest字符数组初始化后内容如下图所示:
    在这里插入图片描述
  2. 第一次拼接后dest字符数组内容如下图所示:
    在这里插入图片描述
  3. 第二次拼接后dest字符数组内容如下图所示:
    在这里插入图片描述
  4. 第三次拼接后dest字符数组内容如下图所示:
    在这里插入图片描述
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值