Hi all!
Is there any short way to get the number of elements in an pointer array?
for example
char *s2[3];
int count = sizeof(s2)/sizeof(s2[0]); shows me 1
Thank you!
Hi all!
Is there any short way to get the number of elements in an pointer array?
for example
char *s2[3];
int count = sizeof(s2)/sizeof(s2[0]); shows me 1
Thank you!
That is strange since it shows 3 to me alright.
I might be wrong.
Quoted more than 1000 times (I hope).Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
This program prints 3, not 1:
The problem is probably because you have passed the array to a function. Since an array decays to a pointer to its first element, sizeof in the function works a pointer, not an array, hence you get 1. One solution is to pass the size of the array as well, and another solution is to designate some special element as the terminator (like how the null character is used to terminate strings).Code:#include <stdio.h> int main() { char *s2[3]; int count = sizeof(s2)/sizeof(s2[0]); printf("%d\n", count); return 0; }
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
Yes sorry I forgot to mention that I pass this pointer array to a function.
But I think its not comfortable to pass the number of elements to a function because it should be a string function and I can never know how many elements I'll pass.
The second solution what you've mentioned is i think the better way but then I must set (before i call the function) the last pointerarrayelement to NULL
thanks
> But I think its not comfortable to pass the number of elements to a function because it should be a string function and I can never know how many elements I'll pass.
fgets() has no trouble with this concept.
And sizeof() needs to see the actual array declaration for this approach to work.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
But there is no solution to this problem.
If it bothers you, you must create a set of functions to manipulate, say, your custom array type that keeps track of the size. This is exactly what C++ has done with its vector class. When you work with the object, it keeps track of its size so you never have to worry.