0

I am trying to print an array using this code.

My expectation would be that it prints out a bunch of 0s but for some reason it is not doing so

int arr[10]; //Initialize all 10 elements to 0
printArray(arr);
void printArray(int in[]) {
    cout << "Array: " << endl;
    for (int i = 0; i < sizeof(in) / sizeof(in[0]); i++) {
        cout << ", " << in[i];
    }
    cout << endl;
}

What am I doing wrong?

J.Doe
  • 1,502
  • 13
  • 47
  • 1
    Since `arr[10]` is local, its elements are not initialized to zero unless you tell the compiler to do so: `arr[0] = {0}` – Sergey Kalinichenko Dec 13 '17 at 18:48
  • With raw arrays, always pass the length. Don't rely on the sizeof trick as it only works in some cases (but you *always* can start by passing the length). – crashmstr Dec 13 '17 at 18:48
  • 1
    Three problems: You *don't* initialize the array; Passing an array to a function lets it decay to a *pointer* to its first element; And lastly, doing `sizeof` on a pointer returns the size of the pointer itself and not to the memory it points to. – Some programmer dude Dec 13 '17 at 18:49
  • @crashmstr That's not entirely true. You can use reference to array types. The reason is usually only works in the same scope as the declaration is that people usually let their array decay to a pointer which loses the size information. – François Andrieux Dec 13 '17 at 18:49
  • You are not using `std::vector`. – Thomas Matthews Dec 13 '17 at 20:38

0 Answers0