Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swap arrays by using pointers in C++

I have two arrays of pointers to doubles that I need to swap. Rather than just copy the data within the arrays, it would be more efficient just to swap the pointers to the arrays. I was always under the impression that array names were essentially just pointers, but the following code receives a compiler error:

double left[] = {1,2,3};
double right[] = {9,8,7};

double * swap = left;
left = right; // Error "ISO C++ forbids assignment of arrays"
right = swap; // Error "incompatible types in assignment of `double*' to `double[((unsigned int)((int)numParameters))]'"

Creating the arrays dynamically would solve the problem, but can't be done in my application. How do I make this work?

like image 626
thornate Avatar asked Aug 03 '10 04:08

thornate


People also ask

How do you do a pointer swap?

Method 1(Swap Pointers) If you are using character pointer for strings (not arrays) then change str1 and str2 to point each other's data. i.e., swap pointers. In a function, if we want to change a pointer (and obviously we want changes to be reflected outside the function) then we need to pass a pointer to the pointer.

Can you swap pointers in C?

Swapping values using pointerSwapping of values of variables by using pointers is a great example of calling functions by call by reference. Functions can be called in two ways: Call by Value. Call by reference.

Does swap work with arrays?

The technique of swapping two variables in coding refers to the exchange of the variables' values. In an array, we can swap variables from two different locations. There are innumerable ways to swap elements in an array.

How do you swap functions in an array?

C++ Array Library - swap() Function The C++ function std::array::swaps() swap contents of the array. This method takes other array as parameter and exchage contents of the both arrays in linear fashion by performing swap operation on induvisual element of array.


2 Answers

double array_one[] = {1,2,3};
double array_two[] = {9,8,7};

double *left = array_one;
double *right = array_two;

double * swap = left;
left = right;
right = swap;

Works nicely.

edit: The definitions array_one and array_two shouldn't be used and the doubleleft and doubleright should be as public as your original left and right definitions.

like image 128
Daniel Avatar answered Oct 11 '22 23:10

Daniel


Arrays are not the same as pointers and cannot be swapped in the way you describe. To do the pointer swap trick, you must use pointers, either dynamically allocate the memory, or use pointers to access the data (in the way Daniel has described).

like image 37
5ound Avatar answered Oct 12 '22 00:10

5ound