目錄
零基礎 C/C++ 學習路線推薦 : C/C++ 學習目錄 >> C 語言基礎入門
一.strcat 函數簡介
前面文章中介紹了關於字符串拷貝的相關函數,例如:strcpy
函數 / strcpy_s
函數/ memcpy
函數 / memcpy_s
函數等等,今天我們將介紹一個新的 C
語言字符串處理函數 strcat
,strcat
函數主要用於字符串拼接,該函數語法如下:
/*
*描述:此類函數是用於對字符串進行拼接, 將兩個字符串連接再一起
*
*參數:
* [in] strSource:需要追加的字符串
* [out] strDestination:目標字符串
*
*返回值:指向拼接后的字符串的指針
*/
//頭文件:string.h
char* strcat(char* strDestination, const char* strSource);
1.strcat
函數把 strSource
所指向的字符串追加到 strDestination
所指向的字符串的結尾,所以必須要保證 strDestination
有足夠的內存空間來容納兩個字符串,否則會導致溢出錯誤。
** 2.strDestination
末尾的** \0
會被覆蓋,strSource
末尾的 \0
**會一起被復制過去,最終的字符串只有一個 \0
** ;
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
內存空間大小 = 目標字符串長度 + 原始字符串場地 + ‘\0’;
獲取內存空間大小使用 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\n", dst); //空字符串
strcat(dst, src);
printf("strcat之后 dst:%s\n", 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\n", dst); //
strcat(dst, src); //dst只有5個字節,如果把src拼接到dst尾部,dst的空間並不能存放下src的所有字符,溢出崩潰
printf("strcat之后 dst:%s\n", dst);
五.猜你喜歡
- 安裝 Visual Studio
- 安裝 Visual Studio 插件 Visual Assist
- Visual Studio 2008 卸載
- Visual Studio 2003/2015 卸載
- 設置 Visual Studio 字體/背景/行號
- C 語言格式控制符/占位符
- C 語言邏輯運算符
- C 語言三目運算符
- C 語言逗號表達式
- C 語言自加自減運算符(++i / i++)
- C 語言 for 循環
- C 語言 break 和 continue
- C 語言 while 循環
- C 語言 do while 和 while 循環
- C 語言 switch 語句
- C 語言 goto 語句
- C 語言 char 字符串
- C 語言 strlen 函數
- C 語言 sizeof 函數
- C 語言 sizeof 和 strlen 函數區別
- C 語言 strcpy 函數
- C 語言 strcpy_s 函數
- C 語言 strcpy 和 strcpy_s 函數區別
- C 語言 memcpy 和 memcpy_s 區別
- C 語言 strcat 函數
未經允許不得轉載:猿說編程 » C 語言 strcat 函數
本文由博客 - 猿說編程 猿說編程 發布!