From what I understand, the C function sizeof(), when given an array, returns the size in bytes of allocated memory to the array. That is, for a declaration unsigned char my_array[10];
, sizeof(my_array);
will return 10.
In C++, vector::size()
similarly returns the number of elements in the vector. In the case of std::vector<unsigned char>
, the number of elements in the vector should theoretically match the number of bytes in the underlying array.
Now, the source of the confusion: I have read that &vector[0]
returns the underlying array from a vector. As such, I would expect that sizeof(&vector[0])
would return the number of elements in the array, if vector were of type std::vector<unsigned int>
.
However, I tested this:
#include <vector>
#include <iostream>
int main() {
std::vector<unsigned char> test_vector;
test_vector.resize(1024);
unsigned char test_array[1024];
std::cout << sizeof(test_array) << '\n';
std::cout << test_vector.size() << '\n';
std::cout << sizeof(&test_vector[0]) << '\n';
}
And it outputs:
1024
1024
8
Why is the behavior of test_vector.size()
and sizeof(&test_vector[0])
different, and where does 8 come from?