0

I was trying to fill the array lebron with elements from the array curry, and then write a function to print the filled array. But the output is not as expected.

My code:

#include <iostream>

using namespace std;

void printArray(int arr[]){
    int arrayLength = sizeof(arr) / sizeof(int);

    cout << "[";

    for(int i=0; i<arrayLength; i++){
        cout << arr[i] << " ";
    }
    cout << "]";
}

int main(){
    int curry[6] = {0, 1, 2, 3, 4, 5};
    int lebron[6];

    for(int i=0; i<6; i++){
        lebron[i] = curry[i];
    }

    printArray(lebron);
}   //end main

The output I expected to be:

[0 1 2 3 4 5]

The actual output:

[0 1 ]
109
  • 1
  • Maybe because size of `int arr[]` is actually size of pointer (8 bytes) and 8/4 = 2, so you get two elements printed. Instead just pass the length of the array as second argument and use it. – kiner_shah Mar 17 '23 at 11:41
  • Or accept the array by reference (usually with templates) and read the size directly. Wouldn't work with pointers (e.g. array allocated with `new`) tho. – Yksisarvinen Mar 17 '23 at 11:45

0 Answers0