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?
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.
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.
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With