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
That's a problem of integer division!
should be
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])
:This works for me (comments explains why):
And the output of this is:
EDIT:
As pointed by @AnorZaken, passing the array to a function as a parameter and printing the result of
sizeof
on it, will output anothertotal
. This is because when you pass an array as argument (not a pointer to it), C will pass it as copy and will apply some C magic in between, so you are not passing exactly the same as you think you are. To be sure about what you are doing and to avoid some extra CPU work and memory consumption, it's better to pass arrays and objects by reference (using pointers). So you can use something like this, with same results as original:It's much more convenient (and less error prone) to use an array length macro:
Use the macros shown in below code to get any dimension size of 1D, 2D or 3D arrays. More macros can be written similarly to get dimensions for 4D arrays and beyond. (i know its too late for Wickerman to have a look but these're for anyone else visiting this page)