Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C, how to print a string from a multidimensional array?

I have the following program to take five user entered names and print them out.

I need to ask for each name one by one, then prompt the user to either print the list of names or add another name to the list. The names must be stored in a two dimensional array, though I don't see why it couldn't be done with a regular array.

My code accepts the names with no issues, but fails to print anything. It includes print tests to monitor where the error happens. Test number 6 does not print, so there must be an issue with printf("Name: %s", names[x][y]);

What is the error?

#include <stdio.h>

    int main() {
    int x;
    int y;
    char names[5][51] = {{'\0'},{'\0'}};

    printf("Enter the names: ");
    for (x = 0; x <5; x++) {
        printf("\nPrintTest 1");
        for (y = 0; y < 1; y++) {
        printf("\nPrintTest 2");
            scanf("%50s",&names[x][y]);
        }
    }
    printf("\nPrintTest 3");

    for (x = 0; x < 5; x++) {
        printf("\nPrintTest 4");
        for (y = 0; y < 1; y++) {
            printf("\nPrintTest 5");
            printf("Name: %s", names[x][y]);
            printf("\nPrintTest 6");
        }
    }
}
like image 876
Naltroc Avatar asked Mar 12 '23 16:03

Naltroc


1 Answers

So here's my analysis

Your Mistake:

In fact you declared a 2D array where each xth index is basically the char*.

  • If you use names[x], it will get the char* pointer at the xth element of names.
  • If you use names[x][y] it will get the pointer at the xth element and then will access it's yth element which is a character and a character datatype is printed by %c not by %s.

Possible Solution:

If you want to print the arrays character by character, then you need to iterate the inner loop over the size of array which is 51 in your case, and then you can print the array by using %c instead of %s.

Or you can print the whole array using %s but in that case inner loop is not required because you will be printing the whole array at a time.

Updated Code:

Method # 01:

//Iterating over all the char*
for (x = 0; x < 5; x++)
{
        printf("\nPrintTest 4");

        //Use of inner loop - Printing the arrays character by character
        for (y = 0; y < 51; y++)
        {
            printf("\nPrintTest 5");
            printf("Name: %c", names[x][y]);
            printf("\nPrintTest 6");
        }
}

Method # 02:

//Iterating over all the char*
for (x = 0; x < 5; x++)
{
        printf("\nPrintTest 4");

        //Printing the arrays without the loop
        printf("\nPrintTest 5");
        printf("Name: %s", names[x]);
        printf("\nPrintTest 6");
}

Hope its clear now.

like image 117
Itban Saeed Avatar answered Mar 23 '23 20:03

Itban Saeed