C語言中字符串的數組的定義實現

方法1,   使用指針數組:

#include   <string.h>
#include   <stdio.h>
#include   <stdlib.h>

int   main()
{
        char   *test[]={ "this   is   a   test ",   "test   2 ",   " "};
        int   i=0;
       
        while(strcmp(test[i],   " ")   !=   0)
                puts(test[i++]);        
       
        system( "PAUSE ");
        return   0;
}

這個方法比較簡單, 但是問題是這樣的話,字符串是常量,無法修改。當然這個問題也可以解決, 比如使用數組賦值, 然後將  char 數組首地址賦值給某一個指針即可。

方法2,使用2維數組:

 

#include   <string.h>

#include   <stdio.h>

#include   <stdlib.h>

int   main()

{

        char   test[][20]={ "this   is   a   test ",   "test   2 ",   " "};

        int   i=0;

        while(strcmp(test[i],   " ")   !=   0)

                puts(test[i++]); 

        system( "PAUSE ");

        return   0;

}

這樣的話, 問題就是   空間的浪費!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章