cmultidimensional-array2dfflush

Last element is missing from the 2D array


Code:

#include <stdio.h>


 int main(){

    int num;

    scanf("%d", &num);
    printf("Enter: ");

    char nums[5][num], ch;

    for(int i = 0; i < num; i++){
        for(int j = 0; j < 5; j++){
            if((ch = getchar()) != '\n'){
                nums[j][i] = ch;
            }
        }
    }


    for(int i = 0; i < num; i++){
        for(int j = 0; j < 5; j++){
            printf("%c ", nums[j][i]);
        }
        printf("\n");
    }

    return 0;
 }

Output:

1
Enter: 12345
 1 2 3 4 

Process returned 0 (0x0)   execution time : 6.282 s
Press ENTER to continue.

Why the last element is missing and the additional space at the beginning of the output of array?

If I change the range for j in both for loops to

j <= 5

then, the output looks like this:

1
Enter: 12345
 1 2 3 4 5 

Process returned 0 (0x0)   execution time : 2.107 s
Press ENTER to continue.

If the initial value for j is 1 in the printf loop, then the output looks like this:

1
Enter: 12345
1 2 3 4 5 

Process returned 0 (0x0)   execution time : 3.675 s
Press ENTER to continue.

No extra gap at the beginning of the array output.

Can anyone explain this and how to resolve this problem?


Solution

  • The problem is that the function getchar reads all characters from the input stream including the new line character that stored in the buffer after the first call of scanf.

    So in the loops the first character that is read is the new line character '\n'. You should remove it for example the following way.

    scanf( "%*[^\n]" );
    scanf( "%*c" );