determine size of array if passed to function

Is it possible to determine the size of an array if it was passed to another function (size isn't passed)? The array is initialized like int array[] = { XXX } ..

I understand that it's not possible to do sizeof since it will return the size of the pointer .. Reason I ask is because I need to run a for loop inside the other function where the array is passed. I tried something like:

for( int i = 0; array[i] != NULL; i++) {
........
}

But I noticed that at the near end of the array, array[i] sometimes contain garbage values like 758433 which is not a value specified in the initialization of the array..


Solution 1:

The other answers overlook one feature of c++. You can pass arrays by reference, and use templates:

template <typename T, int N>
void func(T (&a) [N]) {
    for (int i = 0; i < N; ++i) a[i] = T(); // reset all elements
}

then you can do this:

int x[10];
func(x);

but note, this only works for arrays, not pointers.

However, as other answers have noted, using std::vector is a better choice.

Solution 2:

If it's within your control, use a STL container such as a vector or deque instead of an array.

Solution 3:

Nope, it's not possible.

One workaround: place a special value at the last value of the array so you can recognize it.