Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Find Dimension of a Multiple Dimension Array in C

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?

like image 379
ZZ Coder Avatar asked Sep 18 '09 19:09

ZZ Coder


2 Answers

sizeof array / sizeof array[0]

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;
}


*You need the parens if the operand is a 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.
like image 198
DigitalRoss Avatar answered Oct 05 '22 01:10

DigitalRoss


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? :-)

like image 20
paxdiablo Avatar answered Oct 05 '22 02:10

paxdiablo