Within the scope that array
was declared in, sizeof(array)
is the number of bytes in the array.¹
If you want the number of elements in array
, that’s (sizeof(array)/sizeof(array[0]))
.
Since sizes
is declared as an int*
, sizeof(sizes)
is the size of a pointer. That will be 8 for a 64-bit program, 4 for a 32-bit program, or some other size on an unusual architecture.
There is one other wrinkle: if you pass array
to a function, such as:
int* reverse_array( int a[], const size_t n )
{
assert( sizeof(a) == sizeof(int*) );
// ...
}
Then the array parameter, a
, automatically degrades to a pointer, and the compiler forgets its actual size. This is for backward-compatibility with C.
To use an array within another function, you must pass the size as a separate parameter, in this case n
, or use a type such as std::array<int>
, std::vector<int>
, or a struct
. The latter is what Bjarne Stroustrup’s C++ guidelines recommend, although, if you use a STL template in the ABI of a library, you are introducing a dependency on a particular implementation of the STL.
¹ Since this community loves language-lawyering: some historical C compilers measured sizes in increments other than bytes. Some C++ compiler hypothetically might make char
more than 8 bits wide (although not less!) and claim to be technically conforming to the standard. You don’t need to worry about that possibility right now. Seriously, you don’t.