简体   繁体   中英

Using 2d arrays to store strings in C

I want to make a program that handles strings in 2d arrays in the following manner:

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?

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

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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