Size of multi-dimensional Array

I'm new to the forums -- Hello!

This is an incredibly simple concept so I have no clue why I can't figure it out.

I have a multi-dimensional array as follows:

1
2
3
4
char *szCommands[] = {
	"display",
	"num"
};


*szCommands[0] = "d"
szCommands[0] = "display"
szCommands[1] = "num"

Now, I want to know how many elements of the array there is. I call the sizeof this array and it returns 2 (because there are 2 elements)
You seem to have answered your own question...or I'm not understanding what you are asking.
That is not a multidimensional array. It's a 1D array of pointers.

]code]sizeof(szCommands)[/code] is not 2. It should be 2*sizeof(char*) (ie: 8 on most platforms)


Other than that... I'm with firedraco. What exactly is your question?
That is not a multidimensional array

Each char* in that array is an array of characters
Just figured it out. Thanks to the people who were trying to help. Just to clarify my question, I wanted to know how to get the number of array's in szCommands. It should of been returning 2 (because of "display" (1) and "num" (2)). I was forgetting to put a NULL string in there to "end" it.

1
2
3
4
5
char *szCommands[] = {
	"display",
	"num",
	""
};


1
2
3
int i = 0;
while(szCommands[i] != "") i++;
return i;
Last edited on
BTW, that's not a NULL string. That's an empty string. There is a significant difference.

It is far more common to terminate with a NULL string than an empty string, as an empty string is a valid string, whereas a NULL string is never a valid string.

1
2
3
4
5
const char *szCommands[] = {
        "display",
        "num",
        NULL
};
1
2
3
int i;
while (commands[i]) i++;
return i;

Notice also that it is an array of pointers to const chars. Most modern compilers will accept the syntax without the "const", but the elements will be put in a const data segment anyway -- leading to a runtime failure if you try to modify them. Better to just declare them "const" to begin with (and let the compiler catch attempts to modify it).


If you have access to the array itself (and not a pointer to it), you can also use the sizeof/sizeof trick:
 
int i = sizeof(szCommands)/sizeof(szCommands[0]);
That, however, is something of a trick and the first method is preferable.


There is also another important difference between the two. The first one returns only how many elements there are before the first NULL. The second returns the actual number of elements in the array.

Hope this helps.
Last edited on
Topic archived. No new replies allowed.