How do you get the size of array that is passed into the function?

Viewed 16584

I am trying to write a function that prints out the elements in an array. However when I work with the arrays that are passed, I don't know how to iterate over the array.

void
print_array(int* b)
{
  int sizeof_b = sizeof(b) / sizeof(b[0]);
  int i;
  for (i = 0; i < sizeof_b; i++)
    {
      printf("%d", b[i]);
    }
}

What is the best way to do iterate over the passed array?

8 Answers

Use variable to pass the size of array. int sizeof_b = sizeof(b) / sizeof(b[0]); does nothing but getting the pre-declared array size, which is known, and you could have passed it as an argument; for instance, void print_array(int*b, int size). size could be the user-defined size too.

int sizeof_b = sizeof(b) / sizeof(b[0]); will cause redundant iteration when the number of elements is less than the pre-declared array-size.

The question has already some good answers, for example the second one. However there is a lack of explanation so I would like to extend the sample and explain it:

Using template and template parameters and in this case None-Type Template parameters makes it possible to get the size of a fixed array with any type.

Assume you have such a function template:

template<typename T, int S>
int getSizeOfArray(T (&arr)[S]) {
    return S;
}

The template is clearly for any type(here T) and a fixed integer(S). The function as you see takes a reference to an array of S objects of type T, as you know in C++ you cannot pass arrays to functions by value but by reference so the function has to take a reference.

Now if u use it like this:

int i_arr[] = { 3, 8, 90, -1 };
std::cout << "number f elements in Array: " << getSizeOfArray(i_arr) << std::endl;

The compiler will implicitly instantiate the template function and detect the arguments, so the S here is 4 which is returned and printed to output.

Related