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.