How to determine the size of an array of strings in C++?

Jake Wilson picture Jake Wilson · Feb 16, 2010 · Viewed 20.9k times · Source

I'm trying to simply print out the values contained in an array.

I have an array of strings called 'result'. I don't know exactly how big it is because it was automatically generated.

From what I've read, you can determine the size of an array by doing this:

sizeof(result)/sizeof(result[0])

Is this correct? Because for my program, sizeof(result) = 16 and sizeof(result[0]) = 16 so that code would tell me that my array is of size 1.

However that doesn't appear correct, because if I manually print out the array values like this:

std::cout << result[0] << "\n";
std::cout << result[1] << "\n";
std::cout << result[2] << "\n";
std::cout << result[3] << "\n";
etc...

...then I see the resulting values I'm looking for. The array is upwards of 100+ values in length/size.

It seems like it should be very simple to determine the size/length of an array... so hopefully I'm just missing something here.

I'm a bit of a C++ newb so any help would be appreciated.

Answer

user123456 picture user123456 · Feb 16, 2010

You cannot determine the size of an array dynamically in C++. You must pass the size around as a parameter.

As a side note, using a Standard Library container (e.g., vector) allieviates this.

In your sizeof example, sizeof(result) is asking for the size of a pointer (to presumably a std::string). This is because the actual array type "decays" to a pointer-to-element type when passed to a function (even if the function is declared to take an array type). The sizeof(result[0]) returns the size of the first element in your array, which coincidentally is also 16 bytes. It appears that pointers are 16 bytes (128-bit) on your platform.

Remember that sizeof is always evaluated at compile-time in C++, never at run-time.