tags:

views:

186

answers:

3

Quick c question: How to know the length of a char* foo[]?

Thanks.

+9  A: 

You can't. Not without knowing something about what is inside of the pointers, or storing that data ahead of time.

Robert P
+1, though I wonder how many reincarnations of this very question will be answered without pointing to numerous duplicates.
Tim Post
+4  A: 

You mean the number of strings in the array?

If the array was allocated on the stack in the same block, you can use the sizeof(foo)/sizeof(foo[0]) trick.

const char *foo[] = { "abc", "def" };
const size_t length = sizeof(foo)/sizeof(foo[0]);

If you're talking about the argv passed to main, you can look at the argc parameter.

If the array was allocated on the heap or passed into a function (where it would decay into a pointer), you're out of luck unless whoever allocated it passed the size to you as well.

Nick Meyer
+2  A: 

If the array is statically allocated you can use the sizeof() function. So sizeof(foo)/sizeof(char *) would work. If the array was made dynamically, you're in trouble! The length of such an array would normally be explicitly stored.

EDIT: janks is of course right, sizeof is an operator.

Also it's worth pointing out that C99 does allow sizeof on variable-size arrays. However different compilers implement different parts of C99, so some caution is warranted.

Yuvi Masory
sizeof is an operator, not a function. Using sizeof on an expression (as opposed to the name of a type) doesn't even require braces.
janks