2

I am using sizeof trick to get the length of array, but it only looks like it's adding 1 and 2.

#include <iostream>
#include <stdio.h>
using namespace std;

int add(int array[]) 
{
   int sum = 0;
   for (int i = 0; i < sizeof(array)/sizeof(array[0]); i += 1)
   {
       sum += array[i];
   }
   return sum;
}

int main()
{
    int array[4] = {1, 2, 3, 4};
    cout << add(array);

    return 0;
}

Output is 3. What is wrong?

1 Answers1

4

In a parameter to a function, int array[] is another way of saying int *array, so sizeof(array) will return the size of a pointer-to-int. I’m pretty sure there’s a more idiomatic C++ way of doing this, particularly in the newer versions of C++, but the C way of dealing with this would be to pass a second parameter with the size of the array.

icktoofay
  • 126,289
  • 21
  • 250
  • 231
  • 1
    Re idiomatic C++... using a `std::array` or `vector` is one approach - another is use `template int add(int (&array)[N]) { ... i < N... }`, but then you do get a function instantiation per array size (you can write a thin inline wrapper to pass `N` to an implementation function). – Tony Delroy Aug 22 '14 at 05:04