Lenth of character Array

Hi Experts ,

I have a char array of strings initialized like :-

char *a[] ={"one,"two","three", ..... }

I want to find the number of elements ie strings in this . How can i do that ??
You don't have one string, you have an array of strings.

Do you want the size of the array?
I want the number of strings(elements) in the array at runtime
sizeof(a)/sizeof(char*)
runtime has no effect on an array like this - the size is set at compile time, and you get the number of elements as shown by kbw post above

or
sizeof(a)/sizeof(a[0])
@kbw

If you're going to use sizeof, make sure to mention that he needs a NULL character at the end of the array... otherwise, he could just use strlen(a);
Last edited on
If you're going to use sizeof, make sure to mention that he needs a NULL character at the end of the array
That isn't true.

otherwise, he could just use strlen(a)
That isn't true either. Plus even if it was, a compile time check computation is cheaper than a runtime one.
Thanks Folks ,
The above approach works :)

I have used a similar approach for the fixed size arrays ie sizeof(a)/sizeof(int) but i was not sure how would it manifest for variable length string array . Can anyone throw some light on it
People do get this confused (and I think packetpirate did as well in his post)

Given this:

char *a[] ={"one","two","three", "four" }

The actual array will consist of 4 pointers variables. Each pointer is initialied with the address of the corresponding string from the list.


The character strings being pointed to are NOT part of the array.

Think about it a little.

It is not to be confused with this:

char array[] = "Hello" - which is an array of characters, each char being initialised with the correcponding char from the string.



Last edited on
One thing that wasn't mentioned is that the moment you pass the array to a function, sizeof cannot be used to determine the size of the array any longer. It is important to keep track of the size after its initial creation so that you can pass it along with the array to any function that operates on the array.

On the other hand if you use sequence containers such as std::string, std::vector, std::deque, etc the size information is built into the object which eliminates the need to keep track of size info separately from the array. The drawback to that of course is that you can't use that fun aggregate initialization style with c++.
Topic archived. No new replies allowed.