简体   繁体   English

使用2d数组在C中存储字符串

[英]Using 2d arrays to store strings in C

I want to make a program that handles strings in 2d arrays in the following manner: 我想以下列方式创建一个处理2d数组中字符串的程序:

Each row represents one name only, while columns holds separate characters of each name. 每行仅代表一个名称,而列包含每个名称的单独字符。

Like so: 像这样:

  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

Now, the way I understand arrays is that they work as pointers for the first element. 现在,我理解数组的方式是它们作为第一个元素的指针。 So when I read the string using the readstring(name) function even though I used a 1D array, it should work as a pointer to the 2D array and store each string as I showed above, right? 因此,当我使用readstring(name)函数读取字符串时,即使我使用了1D数组,它应该作为指向2D数组的指针并存储每个字符串,如上所示,对吧?

The following code is supposed to ask for three names then print them all, but it only prints the last name and some gibberish, what did I do wrong? 以下代码应该要求三个名称然后打印所有,但它只打印姓氏和一些乱码,我做错了什么?

#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';

}

The output shows like this: 输出显示如下:

http://i58.tinypic.com/e7i048.jpg http://i58.tinypic.com/e7i048.jpg

The problem is here: 问题出在这里:

readstring(name);

Change it to: 将其更改为:

readstring(name[i]);

The problem is that name is a 2 - d array, or , an array of strings. 问题是name是一个二维数组,或一个字符串数组。 Therefore, to access one string in the array of strings, you need to use an index for that particular string. 因此,要访问字符串数组中的一个字符串,您需要为该特定字符串使用索引。

In fact, the calling function readstring() expects a string as an argument. 实际上,调用函数readstring()需要一个字符串作为参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM