Initializing a multidimensional array and then printing the contents in C

#include <stdio.h>

int main (void)
{

    int weiners[3][2] = {
                       {5, 10, 8},
                       {8, 4, 7},
                       {3, 1, 2},
                       {0, 7, 9}
                     };
    int x,y;

    printf("Weiners:\n_______\n");

    for(x=0;x<=3;++x){
        for(y=0;y<=2;++y){
        printf("%i, ", weiners[x][y]);
        }
        printf("\n");
    }

    return 0;

}

It is simply intended to simply create a small multidimensional array, and then use a loop to print the content. It formats it correctly, and the first three columns are correct, the numbers following them are very wrong. I'm not quite sure what is wrong here.

http://i.stack.imgur.com/TSX2M.png

+3
source share
4 answers

You define int[3][2], and you initialize it 4 x 3, so the last elements are undefined after reaching the loop after the 6th value.

gcc complains about this:

array.c: In function `main':
array.c:7: warning: excess elements in array initializer
array.c:7: warning: (near initialization for `weiners[0]')
array.c:8: warning: excess elements in array initializer
array.c:8: warning: (near initialization for `weiners[1]')
array.c:9: warning: excess elements in array initializer
array.c:9: warning: (near initialization for `weiners[2]')
array.c:10: warning: excess elements in array initializer
array.c:10: warning: (near initialization for `weiners[3]')
array.c:10: warning: excess elements in array initializer
array.c:10: warning: (near initialization for `weiners')
+2
source

Declaring your array is incorrect (it's 4x3 instead of 3x2):

int weiners[4][3] = {
                   {5, 10, 8},
                   {8, 4, 7},
                   {3, 1, 2},
                   {0, 7, 9}
                 };

, 3x2 ( 4x3), for, , :

for(x=0;x<3;++x) {
    for(y=0;y<2;++y) {
+1

[4] [3].

+1

You have specified the wrong number of rows and columns that it should indicate: -

int array[rows][colums]

here row = 4 and columns = 3;

change the loop accordingly.

0
source

All Articles