当前位置:编程学习 > C/C++ >>

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;
}
这样的话, 问题就是   空间的浪费!

作者“成长之路”

补充:软件开发 , C语言 ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,