0

I have a int array. Size of this array is different is main and in toString method.

void toString(int arr[]){
    int size = sizeof(arr)/sizeof(arr[0]);
    cout<<"Size in toString  "<<size<<endl;
    cout<<"{";
    for(int i=0; i<size; i++){
        cout<<arr[i]<<", ";
    }
    cout<<"}"<<endl;
}

int main(){
    int input_arr[] = {1, 2, 3, 4};
    int size_in_main = sizeof(input_arr)/sizeof(input_arr[0]);
    cout<<"Size in main      "<<size_in_main<<endl;
    toString(input_arr);
    return 0;
}

Output:

Size in main      4
Size in toString  2
{1, 2, }

Why is it print different array size?

Rahul
  • 262
  • 1
  • 5
  • 22

2 Answers2

1

A pointer passed as an argument does not have size information. You have to add size as an argument.

Joe Sonderegger
  • 784
  • 5
  • 15
1

In C++, passing an array to a procedure or function call won't create a local copy of the data inside of the array, but rather provide a pointer to the array of data (pass by reference). Because of this, sizeof(arr) will return the size of 'int *', not 'int []'.

This can be resolved by adding a size parameter to your function or procedure that represents the size of the array like so.

void toString(int arr[], int arr_size){
    int size = arr_size/sizeof(arr[0]);
    cout<<"Size in toString  "<<size<<endl;
    cout<<"{";
    for(int i=0; i<size; i++){
        cout<<arr[i]<<", ";
    }
    cout<<"}"<<endl;
}

Which could then be called like this

toString(input_arr, sizeof(input_arr));
Richard Denton
  • 982
  • 2
  • 7
  • 13