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;

}

这样的话, 问题就是   空间的浪费!

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