C语言 如何定义字符串数组
答案:1 悬赏:60
解决时间 2021-10-31 23:55
- 提问者网友:無理詩人
- 2021-10-31 13:29
C语言 如何定义字符串数组
最佳答案
- 二级知识专家网友:野慌
- 2021-10-31 15:00
方法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;
}
这样的话, 问题就是 空间的浪费!
#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;
}
这样的话, 问题就是 空间的浪费!
我要举报
如以上问答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯