Home > Blockchain >  Trying to change first array address using the pass by references technique in C , using 2 methods
Trying to change first array address using the pass by references technique in C , using 2 methods

Time:12-09

I am trying to assign the first array address to another array, by passing the reference of the first array to the change_values(), and changing it inside the function, so that all the first array's values are changed.

For achieving that, I have tried 2 different methods, the first one by using pointers, e.g. int* x = new int(3), and the second one is by using static arrays, e.g. int x[3].

Here is the first method:

#include <iostream>
using namespace std;

void change_values(int*& nums) {
    
    int* nums2 = new int(3);
    
    nums2[0] = 1;
    nums2[1] = 2;
    nums2[2] = 3;
    
    nums = nums2;
}

void print_values(int* nums) {
    cout << nums[0] << "  " << nums[1] << "  " << nums[2];
    cout << endl;
}

int main() {
    
    int* x = new int(3);
    x[0] = 5;
    x[1] = 10;
    x[2] = 15;
    
    change_values(x);
    
    print_values(x);

    return 0;
}

The program outputs : 1 2 3

So the first address of nums was set to the first address to nums2 successfully.

And here is the second method:

#include <iostream>
using namespace std;

void change_values(int (&nums)[3]) {
    
    int nums2[3];
    
    nums2[0] = 1;
    nums2[1] = 2;
    nums2[2] = 3;
    
    nums = nums2;
}

void print_values(int nums[]) {
    cout << nums[0] << "  " << nums[1] << "  " << nums[2];
    cout << endl;
}

int main() {
    
    int x[3];
    x[0] = 5;
    x[1] = 10;
    x[2] = 15;
    
    change_values(x);
    
    print_values(x);

    return 0;
}

The compiler generates an error :

In function 'void change_values(int (&)[3])':
/tmp/Zmp06HOavn.cpp:12:12: error: invalid array assignment
   12 |     nums = nums2;

Can I know why is it giving this error, what should I change to make it succeed using the second syntax?

CodePudding user response:

Can I know why is it giving this error

Because in the second case you're passing an array by reference. That is, the parameter nums in the second case is a reference to an array of size 3 with elements of type int but since we can't assign a built in array to another built in array, we get the mentioned error. Note that in the second case the type of nums is int [3] which is an array type.


On the other hand, in the first case you're passing a pointer by reference. That is, in the first case the parameter nums is actually a reference to a pointer to a non-const int.

Note in this first case, the type of nums is int* which is a pointer type.

  • Related