Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an array of unknown size by reference in c++

Tags:

c++

arrays

merge

I have 4 sorted integer arrays, which i'm trying to merge into one huge sorted array.

I merge A and B together which gives me another int array called X Then I merge C and D together which gives me another int array called Y Finally i merge X and Y together to get Z, which is the final product.

The merge function is doing exactly the same each time, just storing the results into a different array which i want to pass in by reference.

I want to do something like this:

void mergeSort(int arr1[], int arr2, int &result[]){
    ...
}

But i get the error "Array of reference is not allowed". What is the best way to do this?

like image 632
user1636130 Avatar asked Dec 12 '25 11:12

user1636130


2 Answers

The syntax to pass an array by reference in C++ is

int (&result)[size]

note that you need to know the size at compile time. This is probably not what you want to do here and I would suggest to use vector<int>.

like image 110
hivert Avatar answered Dec 15 '25 00:12

hivert


You can not write such a way the function because arrays even if they have elements of the same type but with different sizes are different types.

You need to write a template function

For example

template <size_t N1, size_t N2>

void mergeSort( int ( &arr1 )[N1], int ( &arr2 )[N2], int ( &result )[N1+N2])
{
    ...
}

Otherwise you need to pass to the function sizes of the arrays. For example

void mergeSort( int arr1[], size_t n1, int arr2[], size_t n2, int result[])
{
    ...
}

In this case it is assumed that the size of array result at least is not less than n1 + n2.

like image 37
Vlad from Moscow Avatar answered Dec 15 '25 01:12

Vlad from Moscow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!