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.

I need to query each name one at a time, and then ask the user to either print a list of names, or add another name to the list. Names should be stored in a two-dimensional array, although I do not understand why this cannot be done with a regular array.

My code accepts names without problems, but doesn't print anything. It includes print tests to track where the error occurs. Test number 6 is not printed, so the problem should beprintf("Name: %s", names[x][y]);

What mistake?

#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");
        }
    }
}
+4
source share
2 answers

So here is my analysis

Your mistake:

2D array, xth char*.

  • names[x], char* xth names.
  • names[x][y], xth, yth, , %c %s.

:

, , 51 , , %c %s.

%s , , , .

:

# 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");
        }
}

# 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");
}

, .

+3

y:

char names[5][51];
printf("Enter the names: ");
for (int x = 0; x <5; x++) {
    printf("\nPrintTest 1");
    scanf("%50s", names[x]);
    printf("\nPrintTest 2");
}
printf("\nPrintTest 3");
for (int x = 0; x < 5; x++) {
    printf("\nPrintTest 4");
    printf("Name: %s\n", names[x]);
    printf("\nPrintTest 5");
}
printf("\nDone.\n");

-

+3

Source: https://habr.com/ru/post/1648054/


All Articles