-2

Trying to find the size of an array dynamically. Getting the size while in main() works fine but doesn't when i pass it to the GetSize function.

#include <iostream>
#include <string>

using namespace std;

string GetSize(string array[]);

int main()
{
  string array[] = {"A", "B", "C", "D", "E"};
  int ARRAY_SIZE = (sizeof(array) / sizeof(array[0]));

  cout << "Total Size: " << sizeof(array) << endl;
  cout << "Single Element Size: " << sizeof(array[0]) << endl;

  // Pass the array as an argument to GetSize()
  GetSize(array);
}

string GetSize(string array[])
{
  // Get size of the array
  int ARRAY_SIZE = (sizeof(array) / sizeof(array[0]));

  cout << "Size of array is: " << sizeof(array) << endl;
  cout << "Size of 1st element is: " << sizeof(array[0]);    
}

Output

// Total Size: 160
// Single Element Size: 32
// Size of array is: 8
// Size of 1st element is: 32

I have no clue why the discrepancy between the Total Size and the Size of array.

Repl Sandbox: https://repl.it/@phreelyfe/Size-Of-Error

4UmNinja
  • 510
  • 4
  • 14
  • 1
    There is definitely a few duplicates of this one. – drescherjm Dec 04 '17 at 20:28
  • i've searched stackoverflow for over an hour. none of the duplicates address passing arrays as arguments while getting sizeof – 4UmNinja Dec 04 '17 at 20:28
  • In C++ (from its C heritage), arrays are delicate soap bubbles and turn into a pointer at the drop of a hat. In C++, use a `std::vector` instead, and avoid the problems of arrays. – Eljay Dec 04 '17 at 20:31
  • Addendum: If the size is known at compile time and unchanging thereafter, prefer `std::array` to `std::vector` – user4581301 Dec 04 '17 at 20:32
  • @Eljay i'm still new to this and haven't worked with vector's yet. is it not as simple as passing a pointer reference and converting it in the function? – 4UmNinja Dec 04 '17 at 20:35
  • 1
    The short answer is you need to pass the number of elements to the function along with the pointer. That is if you are not permitted to use c++. if you are permitted to use c++ `std::array` is a better choice. – drescherjm Dec 04 '17 at 20:37
  • I'll have to go with that then. thanks! – 4UmNinja Dec 04 '17 at 20:41

1 Answers1

0

What about

template <typename T, std::size_t N>
constexpr std::size_t getArrSize (const T(&)[N])
 { return N; }

?

I mean: different arrays, with different sizes, are different types.

So you have to explicit the size for the incoming argument.

When you write

string GetSize(string array[])

the compiler consider string array[] as a string * array, so you get sizeof(array) as the size of the pointer (8).

In main() the sizeof(array) is the size of the string[5], so 160.

max66
  • 65,235
  • 10
  • 71
  • 111