0

sizeof(arr) is returning different values from inside main and in arr_size. I expect the array to have all the same properties, I tested that the array isn't completely ruined by accessing a value which worked in all scopes, so I'm at a loss.

#include <iostream>

void arr_size(std::string* arr_) {
    std::cout << sizeof(arr_) << std::endl; // 8
    std::cout << arr[0] << std::endl;
}

int main() {
    std::string arr[100] = {};
    arr[0] = "iiiiiiiiiiiiiii";

    arr_size(arr);

    std::cout << sizeof(arr) << std::endl; // 3200
    std::cout << arr[0] << std::endl;
}

As it shows: the sizeof() the array from within arr_size is 8, while the expected size given from within main is 3200.

Edit, dereferencing arr_ returns the size of std::string, which I would also like to understand.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
user7778287
  • 367
  • 1
  • 11
  • 1
    When your expectations don't match your observation usually your expectations were wrong and it's worth taking a look at [the reference](https://en.cppreference.com/w/cpp/language/sizeof) to check what a class/function/keyword actually does. – Lukas-T Aug 01 '20 at 11:14
  • 2
    arrays can decay to pointers, but arrays are not pointers – 463035818_is_not_an_ai Aug 01 '20 at 11:17
  • @idclev463035818 Why is it that de-referencing the array in the function will give the size of a single element? – user7778287 Aug 01 '20 at 11:26
  • `sizeof(arr_)` is not dereferencing the array. It is the same as `sizeof(std::string*)`. `arr_` is a pointer to a string. `arr` in `main` is a `std::string[100]`, you need to understand that those are different types. – 463035818_is_not_an_ai Aug 01 '20 at 11:32
  • 1
    or maybe you were refering to code that isnt included in your post. `sizeof( *arr_)` is the same as `sizeof ( std::string)` because `*arr_` is `std::string` – 463035818_is_not_an_ai Aug 01 '20 at 11:33
  • It's very unintuitive that de referencing a pointer gives different properties than the original object, but I guess it makes sense. Interested in solutions which are more elegant than adding a function parameter if that's even possible in c++. – user7778287 Aug 01 '20 at 11:42
  • 1
    @user7778287 You may want to pass a `std::array const&`. Or, if you want to stick to your array, pass it as reference: `template void arr_size(T const (&arr)[N]) { /* ... */ }` – bitmask Aug 01 '20 at 11:53

0 Answers0