find the size of string array

Hello
assuming we have the next decleration:
char *str_arr[]={"hello", "foo", "bar"};
How can we programatically find the number of elements of that array? (which in this case is 3)
Thanks in advance.
sizeof(str_arr)/sizeof(char*)
note this will not work char** arr_ptr = str_arr or if you pass str_arr into a function.
Last edited on
Gah!

People! sizeof is a bad solution!

note this will not work char** arr_ptr = str_arr or if you pass str_arr into a function.


Which is exactly why you shouldn't use sizeof for this, because it will still compile OK and just give you runtime errors.

use this instead:

1
2
3
4
5
6
7
8
9
10
template <typename T,unsigned S>
unsigned arraysize(const T (&v)[S]) { return S; }


int main()
{
    const char* str_arr[]={"hello","foo","bar"};

    cout << arraysize(str_arr);  // prints "3"
}
Last edited on
What is with this site today, is everyone missing that part in the upper leftish corner where it says "Beginners"?

In Dischs code Line one declares what is called a "Template" (http://www.cplusplus.com/doc/tutorial/templates/) which could be thought of as a function that hasn't made up its mind about what it is yet. The "typename T" tells the Template that what ever I send here, I will refer to as 'T'. The part that reads "unsigned S" tells the template to also expect and unsigned integer here that we will refer to as 'S'.

The part below that is where the coolness that is C++ shows through, this is a function for the template named arraysize, that returns an unsigned integer. For the arguments to arraysize we have a constant value for T with an argument of "(&v)" this refers to our string "str_arr[]" in our code and within the "[]" brackets is an argument "S" which is returned from inside the function. This says take everything about the Class String (http://www.cplusplus.com/reference/string/string/) and return to me the size of the array laid out for this particular instance of it.

If I explained anything wrong please let me know, I'm not always good at explaining my thought process.
Last edited on
Topic archived. No new replies allowed.