Swap arrays by using pointers in C++

thornate picture thornate · Aug 3, 2010 · Viewed 35.3k times · Source

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?

Answer

Daniel picture Daniel · Aug 3, 2010
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.