-1

In the below simple c++ program, I'm trying to get the length of an array by using sizeof, for same array, why when passing the array as an argument to a function the array length becomes incorrect? How should I get the length of an array who is an argument of a function?

#include <iostream>

int get_length(int arr[]){
  return sizeof(arr)/sizeof(*arr);
}

int main(){
  int arr[] = {5,10,15,20};
  std::cout << "non function call: " << sizeof(arr)/sizeof(*arr) << std::endl;
  std::cout << "function call: " << get_length(arr) << std::endl;
}

running result:

non function call: 4
function call: 2
msn
  • 437
  • 1
  • 5
  • 11

2 Answers2

2

when passing the array as an argument to a function the array length becomes incorrect?

Despite appearances, the function parameter is a pointer (to the first array element), not an array. You get the ratio of the size of a pointer to the size of int, which happens to be 2 on your platform.

There's no way to determine the size of an array given just a pointer.

How should I get the length of an array who is an argument of a function?

Arrays can't be passed by value to a function, and only arrays of known size can be passed by reference. So you'll need a template to infer the size of any array from the function argument:

template <typename T, size_t N>
size_t get_length(T (&)[N]) {return N;}

In C++14 or later, this function is available in the standard library, and is called std::size. It's overloaded to work for both arrays and STL-style containers with a size member function.

Alternatively, you might consider using std::array (or std::vector when you need a dynamic/resizable array), rather than a quirky built-in array.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • Mike you might want to change `get the ration of the size` to `get the ratio of the size`. It wont let me edit it since it needs to be at least 6 characters. – NathanOliver Feb 16 '15 at 14:43
  • Yeah I am not sure why it wont let me fix a simple typo. Maybe I don't have enough rep to do that. – NathanOliver Feb 16 '15 at 14:46
  • @NathanOliver: Yes, that's correct. Your edit would have to be a "suggested edit" due to your low rep, and those are required to be substantial to avoid bloating the review queues. You did the right thing here; thank you! – Lightness Races in Orbit Feb 16 '15 at 14:57
  • @LightnessRacesinOrbit: No problem. It tripped me up when reading the answer so I wanted to make sure it was fixed. – NathanOliver Feb 16 '15 at 15:00
0

When you pass array to a function, the array decay to a pointer, so when you do sizeof(arr) in the function, you are asking the size of a pointer.

To make sure it doesn't decay, do it like this:

int get_length(int (&arr)[4]){
...
}

See this question for more about arrays.

If you want to pass an array that can be any size, use a std::vector.

Community
  • 1
  • 1
swang
  • 5,157
  • 5
  • 33
  • 55