我想制作一个程序,以以下方式处理二维数组中的字符串:
每一行仅代表一个名称,而列包含每个名称的单独字符。
就像这样:
0 1 2 3 4 5
0 K e v i n \0
1 J o h n \0
2 L u c y \0
现在,我理解数组的方式是它们作为第一个元素的指针。所以,当我使用read string(name)函数读取字符串时,即使我使用的是1D数组,它也应该作为指向2D数组的指针,并像上面所示那样存储每个字符串,对吧?
下面的代码应该要求输入三个名字,然后全部打印出来,但它只打印姓氏和一些胡言乱语,我做错了什么?
#include <stdio.h>
#include <stdlib.h>
void readstring(char name[]);
void get_data(char name[][15]);
void show_data(char name[][15]);
int main()
{
char name[3][15];
get_data(name);
show_data(name);
return 0;
}
void get_data(char name[][15]){
int i=0;
for(i=0;i<3;i++){
printf("\nEnter name: ");
readstring(name);
}
}
void show_data(char name[][15]){
int i;
for(i=0;i<3;i++){
printf("%s",name[i]);
}
}
void readstring(char str[]){
int i=0;
while((str[i++]=getchar())!='\n' && i<15);
str[i]='\0';
}
输出显示如下:
http://i58.tinypic.com/e7i048.jpg
最佳答案
问题在于:
readstring(name);
更改为:
readstring(name[i]);
问题是
name
是一个二维数组或字符串数组。因此,要访问字符串数组中的一个字符串,需要为该字符串使用索引。实际上,调用函数
readstring()
需要一个字符串作为参数。关于c - 使用2D数组在C中存储字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30150833/