Given your array of strings, you can most certainly use sizeof(array)/sizeof(array[0])
to get its size and the following program works just fine:
int main()
{
std::string array[] = { "S1", "S2", "S3" };
std::cout << "A number of elements in array is: "
<< sizeof(array)/sizeof(array[0]) << '\n';
foo(array);
}
It is not clear what do you mean by saying that size of elements vary. Size of the elements of any array is always known at compiler-time, no exceptions.
There are, however, situations where the above will not work. Consider the following example:
void foo(std::string array[])
{
std::cout << "A number of elements in array is: "
<< sizeof(array)/sizeof(array[0]) << '\n';
}
The above code is doomed to fail. It might look a bit weird at first, but the reason for this is actually very simple — this is called array decaying. It means that every time you pass an array to a function, its type is automatically decayed to that of a pointer. So the above function is in fact an equivalent of this:
void foo(std::string *array)
{
}
And if in the first example the sizeof
operator returns the total size of an array, in the second example it returns the size of a pointer to that array, which is a totally different thing.
There are usually two ways people go about it. The first is to add a special “last” element of the array so that application can traverse the array until it sees the last element and calculate the array’s length. String literals are the perfect example of this — every string literal ends with ‘\0’ and you can always calculate its length. Here is an example:
static void foo(const std::string *array)
{
size_t i = 0;
while (!array[i].empty())
++i;
std::cout << "Array length is: " << i << std::endl;
}
The downside is obviously a need to traverse the array to determine its length. The second way it to always carry array length around, for example:
static void foo(const std::string *array, size_t length)
{
// ...
}
void bar()
{
std::string array[] = { "S1", "S2", "S3" };
foo(array, sizeof(array)/sizeof(array[0]));
}
In C++, you can use a template to deduct array’s length, for example:
template <size_t array_length>
static void foo(const std::string (&array)[array_length])
{
std::cout << "A number of elements in template array is: "
<< array_length << '\n';
}
All of the above applies to simple arrays that are built-in into the language. C++, on the other hand, provides a rich set of higher-level containers that give you a lot of flexibility. So you might want to consider using one of the containers that are available to you as part of C++ Standard Library. For a list of standard containers, see — http://en.cppreference.com/w/cpp/container
Hope it helps. Good Luck!
std::vector
, or astd::array
if your compiler supports it. – Boulder