目錄
- 一.strcat 函式簡介
- 二.strcat 函式原理
- 三.strcat 函式實戰
- 四.注意 strcat 函式崩潰問題
- 五.猜你喜歡
零基礎 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 函式
本文由博客 - 猿說編程 猿說編程 發布!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/345472.html
標籤:C
上一篇:C++實作一個SOAP客戶端
