6/22/08

Calculating the Size of an Incomplete Array An incomplete array declaration can appear in a function's parameter list.

Calculating the Size of an Incomplete Array An incomplete array declaration can appear in a function's parameter list. For example:

int count(const char s[]);

The declaration of s doesn't include the array's size. Can count() use the operator sizeof to calculate the size of s? No, it can't. The compiler implicitly transforms an array into a pointer. Therefore, sizeof returns a pointer's size, not an array's size. One way to obtain the array's size is to pass an additional argument that holds the number of elements in the array:
int count(const char s[], int arr_size);
However, this solution is error prone. A better solution is to pass a vector and call its size() member function:
int count(const vector &s )
{
return s.size();
}

No comments: