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?
Example:*
#include <stdio.h>
int main(void) {
int array[4];
printf("%zd\n", sizeof array / sizeof array[0]);
printf("%zd\n", sizeof (int));
printf("%ld\n", (long)(sizeof array / sizeof array[0]));
return 0;
}
type-name
, even though sizeof
is an operator not a function. But every place where a type-name
appears in the C grammar (declarators don't use that production) then parens are required around it. Because there isn't a separate production for a type-name-in-parens in the semi-formal grammars used for the various C specs, they specify the needed parens in the productions that define things like sizeof
, generic-associations
, and cast-expressions
. But those parens are really there in order to be able to parse a type within the expression grammar. They are part of the syntax for something you might call "type expressions," but given the limited use of such things they don't actually have any such production or term.
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? :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With