That’s because the size of an int *
is the size of an int pointer (4 or 8 bytes on modern platforms that I use but it depends entirely on the platform). The sizeof
is calculated at compile time, not run time, so even sizeof (arr[])
won’t help because you may call the foo()
function at runtime with many different-sized arrays.
The size of an int array is the size of an int array.
This is one of the tricky bits in C/C++ – the use of arrays and pointers are not always identical. Arrays will, under a great many circumstances, decay to a pointer to the first element of that array.
There are at least two solutions, compatible with both C and C++:
- pass the length in with the array (not that useful if the intent of the function is to actually work out the array size).
- pass a sentinel value marking the end of the data, e.g.,
{1,2,3,4,-1}
.