Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't the array being passed by reference?

Tags:

c++

Why is it that x prints out 1,2,3,4 instead of 4,3,2,1. When i print input[0] it says 4. Shouldn't the array have been passed by reference? So I can use x to refer to input which was originally x? This is C++ by the way. This is not a duplicate of the other question. If I print out the array in rev listo, it prints correctly. The issue is in terms of the array being callable in the main function.

using namespace std;

void rev_listo(int input[], int num)
{
    int end_list[num];

    for (int x = 0; x<num; x++) {
        end_list[x]=input[num-x-1];
        // cout<<end_list[x]<<endl;
    }
    // std::cout<<input<<std::endl;

    input=end_list;
    cout<<input[0]<<endl;
}

int main() {
    int x [4];
    x[0]=1;
    x[1]=2;
    x[2]=3;
    x[3]=4;

    rev_listo(x,  4);

    for(int y = 0; y<4; y++) {
        std::cout<<x[y]<<std::endl;
    }

    return 0;
 }
like image 482
AxtonTheGreat Avatar asked Jan 27 '23 18:01

AxtonTheGreat


1 Answers

Internally, When you do void rev_listo(int input[], int num), a pointer pointing to first element of the array is passed (just to avoid copying of array).

Like this:

void rev_listo(int *input /* = &(arr[0])*/, int num)

Please note that the input pointer itself is copied by value, not by reference. So, When you do this, address of first element of end_list is copied to input pointer.:

input=end_list;

When the function ends, the pointer input dies.

void rev_listo(int input[], int num)
{

    int end_list[num];

    for(int x = 0; x<num; x++){
       end_list[x]=input[num-x-1];
    //cout<<end_list[x]<<endl;
    }
   // std::cout<<input<<std::endl;

    input=end_list;
   cout<<input[0]<<endl;
} // input pointer dies here. So does num.

Instead of just assigning the pointer like this: input=end_list; , you should copy the array manually. Like this:

for(int x = 0; x<num; x++){
   input[x] = end_list[x];
}
like image 55
Kunal Puri Avatar answered Jan 29 '23 08:01

Kunal Puri