Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

assigning new array to reference variable

void byReference(int (&p)[3]){
    int q[3] = {8, 9, 10};
    p = q;
}

I want to write function where i can reassign the p with new array. I am not sure if we can do that.

My goal :
i want to change the original array, like we do swapping of two number by call-by reference.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In c++ it is recomended to use std::array for fixed size arrays, and std::vector for a dynamic size arrays.

Both of them can be passed by refernce, to be modified by a function.
This requires the function to declare that the argument is passed by refernce using the & symbol.

See the example below:

#include <array>
#include <vector>

// Get an array (with a fixed size of 3) by refernce and modify it:
void ModifyStdArray(std::array<int, 3> & a) {
    a = std::array<int, 3>{8, 9, 10};
    // or:
    a[0] = 8;
    a[1] = 9;
    // etc.
}

// Get a vector by refernce and modify it:
void ModifyStdVector(std::vector<int> & v) {
    v = std::vector<int>{ 1,2,3,4 };
    // or:
    v.clear();
    v.push_back(1);
    v.push_back(2);
    // etc.
}

int main()
{
    std::array<int, 3> a1;
    // Pass a1 by reference:
    ModifyStdArray(a1);
    // Here a1 will be modified.

    std::vector<int> v1;
    // Pass v1 by reference:
    ModifyStdVector(v1);
    // Here v1 will be modified.
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading