0

This definitely has a really simple answer, but I can't work it out. I've just made a simple function that outputs an array, but it only ever outputs the first two values of the array. I think it has something to do with the way I'm passing the array into the function.

#include <iostream>

using namespace std;


void outputArray(int arrayOut[]){

    int size = sizeof(arrayOut)/sizeof(arrayOut[0]);//size is only 2??
    cout << "{";
    for(int i = 0; i < size; i++){
        cout << arrayOut[i];
        if(i != size-1){
            cout << ", ";
        }
    }
    cout << "}";
}

int main(){
    int myArr[6] = {0, 1, 2, 3, 4, 5};
    outputArray(myArr);
    return 0;
}

Thank you very much!

user2635139
  • 59
  • 1
  • 2
  • 7
  • 1
    You should read this: http://stackoverflow.com/questions/4810664/how-do-i-use-arrays-in-c It will explain everything you should know about arrays – Amadeus Aug 20 '16 at 00:49
  • 1
    You would normally pass the length of the array (6) as a second parameter. Also, `i` needs to be initialized to `0`. – 0x499602D2 Aug 20 '16 at 00:56
  • Maybe because `sizeof(int) = 4` and `sizeof(int*) = 8` in your system. – MikeCAT Aug 20 '16 at 01:01

1 Answers1

1

Array variables are treated like pointers, so sizeof(arrayOut) is actually returning the size of the pointer arrayOut, not the size of the array. In 64-bit code, pointers are 8 bytes. sizeof(arrayOut[0]) returns the size of int, which is 4 bytes. So you get 2.

As @0x499602D2 states in their comment, you need to pass the array length as a separate parameter.

smead
  • 1,660
  • 12
  • 22