1

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?

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
  • 1
    Hint: `&test_vector[0]` gives you a pointer – NathanOliver Aug 10 '21 at 19:25
  • `sizeof` isn't a function. It's an operator that takes any expression and returns the size of the **type** of that expression relative to the size of `char`. – Brian61354270 Aug 10 '21 at 19:26
  • 6
    _"I have read that `&vector[0]` returns the underlying array"_. It does not. It produces a pointer to `vector[0]`. – Drew Dormann Aug 10 '21 at 19:27
  • 2
    Potential duplicate: [Is an array a pointer?](https://stackoverflow.com/questions/1641957/is-an-array-name-a-pointer) – Drew Dormann Aug 10 '21 at 19:29
  • 1
    FYI, if you really want to get a pointer to `std::vector`'s underlying storage, using [`std::vector::data()`](https://en.cppreference.com/w/cpp/container/vector/data) is more clear. – Brian61354270 Aug 10 '21 at 19:32
  • 1
    @Drew Agreed. I also found another complementary duplicate. Feel free to suggest others. – Adrian Mole Aug 10 '21 at 19:33
  • @DrewDormann Okay, that clears things up a bit. Is there a way, then, to retrieve the underlying array, as opposed to a pointer to the first element? I know vector::data() returns a pointer to the first element of the array, also. – HUNTER CROSLAND Aug 10 '21 at 19:33
  • 4
    @HUNTERCROSLAND There is no 'underlying array' - in terms of something like a *declared* array. The vector has a *pointer* as one of its internal members, and that points to dynamically allocated memory. – Adrian Mole Aug 10 '21 at 19:35
  • @AdrianMole Okay, that makes sense. Thank you! – HUNTER CROSLAND Aug 10 '21 at 19:35

0 Answers0