C语言 strcat 函数

目录

零基础 C/C++ 学习路线推荐 : C/C++ 学习目录 >> C 语言基础入门

一.strcat 函数简介

前面文章中介绍了关于字符串拷贝的相关函数,例如:strcpy 函数 / strcpy_s 函数/ memcpy 函数 / memcpy_s 函数等等,今天我们将介绍一个新的 C 语言字符串处理函数 strcatstrcat 函数主要用于字符串拼接,该函数语法如下:

/*
*描述:此类函数是用于对字符串进行拼接, 将两个字符串连接再一起
*
*参数:
*   [in] strSource:需要追加的字符串
*   [out] strDestination:目标字符串
*
*返回值:指向拼接后的字符串的指针
*/

//头文件:string.h

char* strcat(char* strDestination, const char* strSource);

1.strcat 函数strSource 所指向的字符串追加到 strDestination 所指向的字符串的结尾,所以必须要保证 strDestination 有足够的内存空间来容纳两个字符串,否则会导致溢出错误。

** 2.strDestination末尾的** 会被覆盖,strSource末尾的 **会一起被复制过去,最终的字符串只有一个 ** ;

3.如果使用 strcat 函数提示 error:4996,解决办法请参考:error C4996: ‘fopen’: This function or variable may be unsafe

error C4996: 'strcat': This function or variable may be unsafe.
Consider using strcat_s instead. To disable deprecation,
use _CRT_SECURE_NO_WARNINGS. See online help for details.

二.strcat 函数原理

strcat 函数原理:dst 内存空间大小 = 目标字符串长度 + 原始字符串场地 + ‘’;

获取内存空间大小使用 sizeof 函数(获取内存空间大小)获取字符串长度使用 strlen 函数(查字符串长度)

三.strcat 函数实战

/******************************************************************************************/
//@Author:猿说编程
//@Blog(个人博客地址): www.codersrc.com
//@File:C语言教程 - C语言 strcat 函数
//@Time:2021/06/06 08:00
//@Motto:不积跬步无以至千里,不积小流无以成江海,程序人生的精彩需要坚持不懈地积累!
/******************************************************************************************/

#include "stdafx.h"
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include "windows.h"
//error C4996: 'strcat': This function or variable may be unsafe. Consider using strcat_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
#pragma warning( disable : 4996)
void main()
{
    char src[1024] = { "C/C++教程-strcat函数" };
    char dst[1024] = { "www.codersrc.com"};
    printf("strcat之前 dst:%s
", dst); //空字符串
    strcat(dst, src);
    printf("strcat之后 dst:%s
", dst);//
    system("pause");
}
/*
输出结果:
strcat之前 dst:www.codersrc.com
strcat之后 dst:www.codersrc.comC/C++教程-strcat函数
请按任意键继续. . .
*/

四.注意 strcat 函数崩溃问题

char src[1024] = { "C/C++教程-strcat函数" };
char dst[5] = { "www"};

printf("strcat之前 dst:%s
", dst); //
strcat(dst, src); //dst只有5个字节,如果把src拼接到dst尾部,dst的空间并不能存放下src的所有字符,溢出崩溃
printf("strcat之后 dst:%s
", dst);

五.猜你喜欢

  1. 安装 Visual Studio
  2. 安装 Visual Studio 插件 Visual Assist
  3. Visual Studio 2008 卸载
  4. Visual Studio 2003/2015 卸载
  5. 设置 Visual Studio 字体/背景/行号
  6. C 语言格式控制符/占位符
  7. C 语言逻辑运算符
  8. C 语言三目运算符
  9. C 语言逗号表达式
  10. C 语言自加自减运算符(++i / i++)
  11. C 语言 for 循环
  12. C 语言 break 和 continue
  13. C 语言 while 循环
  14. C 语言 do while 和 while 循环
  15. C 语言 switch 语句
  16. C 语言 goto 语句
  17. C 语言 char 字符串
  18. C 语言 strlen 函数
  19. C 语言 sizeof 函数
  20. C 语言 sizeof 和 strlen 函数区别
  21. C 语言 strcpy 函数
  22. C 语言 strcpy_s 函数
  23. C 语言 strcpy 和 strcpy_s 函数区别
  24. C 语言 memcpy 和 memcpy_s 区别
  25. C 语言 strcat 函数

未经允许不得转载:猿说编程 » C 语言 strcat 函数

本文由博客 - 猿说编程 猿说编程 发布!

原文地址:https://www.cnblogs.com/shuopython/p/15142595.html