在軟體開發項目中,經常有程式要對字串進行操作。為此,C函數庫中提供了一些用來對字串進行處理的函數,使用起來非常的方便。但由於字串都有長度,如果隨意對不同的字串進行串連和拷貝等操作,就可能出現意想不到的後果。
因此,在實際開發過程中,十分強調對字串處理函數進行異常保護。本文詳細介紹如何正確運用字串處理函數進行C程式設計。
1. strcat和strncat函數
strcat函數的作用是串連兩個字元數組中的字串。在MSDN中,其定義為:
char *strcat( char *strDestination, const char *strSource );
Remarks: The strcat function appends strSource to strDestination and terminates the resulting string with a null character. The initial character of strSource overwrites the terminating null character of strDestination. It returns the destination string (strDestination).
strcat函數將strSource字串拼接到strDestination後面,最後的傳回值是拼裝完成之後的字串strDestination。
這裡有一個問題,如果字串strSource的長度大於了strDestination數組的長度,就會出現數組越界的錯誤,程式就會崩潰。如下代碼所示:
/*************************************************************** *著作權 (C)2014, Zhou Zhaoxiong。 * *檔案名稱:StrcatTest.c *內容摘要:用於測試strcat函數 *其它說明:無 *目前的版本:V1.0 *作 者:周兆熊 *完成日期:20140405 * *修改記錄1: //修改記錄,包括修改日期、版本號碼、修改人及修改內容等 * 修改日期: * 版本號碼: * 修改人: * 修改內容: ***************************************************************/ #include <stdio.h> #include <string.h> typedef signed char INT8; //重定義資料類型 typedef signed int INT32; //重定義資料類型 /********************************************************************** *功能描述:主函數 *輸入參數:無 *輸出參數:無 *傳回值:無 *其它說明:無 *修改日期 版本號碼 修改人 修改內容 * ------------------------------------------------------------------------------------------ * 20140405 V1.0 周兆熊 建立 ***********************************************************************/ INT32 main(void) { INT8 szStrDestination[10] = "Hello"; INT8 szStrSource[10] = "Hello123"; //先列印源字串和目的字串 printf("The source string is: %s\n", szStrSource); printf("The destination string is: %s\n", szStrDestination); strcat(szStrDestination, szStrSource); //調用strcat函數 //列印拼裝完成之後的字串 printf("The changed destination string is: %s\n", szStrDestination); return 0; }