1

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

1
  • 1
    Pay attention to compiler warnings. They would show you exactly where the problem is here. Commented May 10, 2015 at 11:32

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

"not an array of strings" is not right as name, in get_data is not a 2D array. It is a pointer to an array of 15 chars in get_data.
Oh! Took me some time to understand why it works now, but thanks!
@CoolGuy: Thanks! I missed that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.