C: Size of two dimensional array

Wickerman picture Wickerman · Dec 7, 2015 · Viewed 109.1k times · Source

I need some help counting the rows and columns of a two dimensional array. It seems like I can't count columns?

#include <stdio.h>

int main() {

char result[10][7] = {

    {'1','X','2','X','2','1','1'},
    {'X','1','1','2','2','1','1'},
    {'X','1','1','2','2','1','1'},
    {'1','X','2','X','2','2','2'},
    {'1','X','1','X','1','X','2'},
    {'1','X','2','X','2','1','1'},
    {'1','X','2','2','1','X','1'},
    {'1','X','2','X','2','1','X'},
    {'1','1','1','X','2','2','1'},
    {'1','X','2','X','2','1','1'}

};

int row = sizeof(result) / sizeof(result[0]);
int column = sizeof(result[0])/row;

printf("Number of rows: %d\n", row);
printf("Number of columns: %d\n", column);

}

Output:
Number of rows: 10
Number of columns: 0

Answer

Marcus M&#252;ller picture Marcus Müller · Dec 7, 2015

That's a problem of integer division!

int column = sizeof(result[0])/row;

should be

int column = 7 / 10;

and in integer division, 7/10==0.

What you want to do is divide the length of one row, eg. sizeof(result[0]) by the size of one element of that row, eg. sizeof(result[0][0]):

int column = sizeof(result[0])/sizeof(result[0][0]);