Quick c question: How to know the length of a char* foo[]?
Thanks.
You can't. Not without knowing something about what is inside of the pointers, or storing that data ahead of time.
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.
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.
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