C语言 如何定义字符串数组

例如string username[4]={"hoho","hohn","saturn","mike"} //本意是username[0]=hoho username[1]=hohn 怎么在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;
}
这样的话,
问题就是
空间的浪费!
温馨提示:答案为网友推荐,仅供参考
相似回答