例如string username[4]={"hoho","hohn","saturn","mike"}
//本意是username[0]=hoho
username[1]=hohn
怎么在C语言中实现呢。
本人已经自己解决,,,
用二维数祖或指针数组,都可以了。。
C语言字符串数组中的每一个元素均为指针,即有诸形如“ptr_array[i]”的指针。由于数组元素均为指针,因此ptr_array[i]是指第i+1个元素的指针。
例:如二维指针数组的定义为:char *ptr_array[3]={{"asdx","qwer","fdsfaf"},{"44444","555","6666"},{"a78x","q3er","f2f"}};
扩展资料
字符串数组数组元素表示方法:
数组元素的一般形式为:数组名[下标] 其中的下标只能为整型常量或整型表达式。如为小数时,C编译将自动取整。
例如,a[5],a[i+j],a[i++]都是合法的数组元素。数组元素通常也称为下标变量。必须先定义数组, 才能使用下标变量。在C语言中只能逐个地使用下标变量, 而不能一次引用整个数组。
参考资料来源:百度百科—指针数组
温馨提示:答案为网友推荐,仅供参考
第1个回答 推荐于2017-10-10
方法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;
}
这样的话, 问题就是 空间的浪费!
第2个回答 2006-12-14
char username[n][4]={"hoho","hohn","saturn","mike"};
n是字符串的个数本回答被提问者采纳
n是字符串的个数本回答被提问者采纳
第3个回答 2019-12-23
10.3.1-C程序设计基础-字符数组与字符串
第4个回答 2021-01-01
C语言字符串的学习,输入指定字符串,并且计算字符串的位数