提前認識軟體開發(10) 字串處理函數及異常保護

來源:互聯網
上載者:User

在軟體開發項目中,經常有程式要對字串進行操作。為此,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;    }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.