I declared a 2-dimensional array like this:
char *array[][3] = {
{"a", "b", "c"},
{"d", "e", "f"},
{"u", "v", "w"},
{"x", "y", "z"}};
How do I find out the first dimension?
I declared a 2-dimensional array like this:
char *array[][3] = {
{"a", "b", "c"},
{"d", "e", "f"},
{"u", "v", "w"},
{"x", "y", "z"}};
How do I find out the first dimension?
Why don't you give:
sizeof(array) / sizeof(char*) / 3
a shot?
This is assuming you know the data type (char*) and other dimension (3).
You divide the size of the structure by the size of each element to get the total number of elements, then divide it by the first dimension, giving you the second.
Aside: my original answer used 'sizeof("a")'
which was, of course, wrong, since it was the size of the array (2, being 'a' and '\0'), not the pointer (4 on my hideously outdated 32-bit machine). But I love the way I got two upvotes for that wrong answer - don't you bods actually check the answers here before voting? :-)
BTW, please don't worry about the lack of function-like parens following sizeof. It's really an operator; those parens have always been optional. I did test this expression with the following program:
printf("%zd\n", sizeof array / sizeof array[0]);
(Use %d
btw for C89.)