-1
#include <iostream>
using namespace std;
void print(int a[])
{
    int size = sizeof(a)/sizeof(int);
    for ( int i = 0; i < size; i++){
        cout << a[i] << " ";
    }


}
int main()
{
    int a[] = {3, 4, 5, 0, 0, 1};
    print(a);
}

It's a simple function and i think my aim is obvious.Everything seems to be in order for me however function only prints the first value of the array.I tried returning size and check it's value and it is 1.This explains why it's only printing the first value of the array.

So what am i doing wrong guys?

SpiderRico
  • 1,890
  • 8
  • 28
  • 48
  • a is pointer and it will return only size of first element. (Usually 4 bytes). You need to pass size of an array to function. @Arne that solution is risky and can not be generally applied. – Dejan Jun 07 '13 at 12:54
  • Surprise! The `a` parameter in `print` is a pointer, not an array at all. – aschepler Jun 07 '13 at 12:56
  • Two excellent reasons why `std::array` is better: It doesn't decay to a pointer and confuse people, and it knows its size. – chris Jun 07 '13 at 13:14

1 Answers1

0

You cannot pass an array by value in C++, it decays to a pointer to its first element. The following signatures are 100% semantically equivalent:

void print(int a[]);
void print(int *a);

You can turn the function into a funciton template and accept the array by reference:

template <size_t N>
void print(int (&a)[N])
{
  for (size_t i = 0; i < N; ++i) {
    cout << a[i] << ' ';
  }
}
Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
  • So that means the function has to know the size of array when it's passed?So basically there's no way for to compute an array's size inside a function, rite? – SpiderRico Jun 07 '13 at 13:12
  • @user2362377 In a function, just like anywhere else, the size of an array can be computed by `sizeof(array) / sizeof(element)`. However, in a function `void foo(int a[])`, `a` is *not* an array, it's a *pointer.* Even if that pointer was originally created by decaying from an array, it's a pointer, so there's no way to recover the "original" array inside the function. There doesn't even have to be one: your original `print` can perfectly legally be called as `int i = 0; print(&i);`. – Angew is no longer proud of SO Jun 07 '13 at 13:26