0

I'd like to swap two integer arrays without copying their elements :

int  Z1[10],Z2[10];
std::swap(Z1,Z2);  // works
//int *tmp;*tmp=*Z1;*Z1=*Z2;*Z2=*tmp; // doesn't work
[ expressions involving Z1,Z2 ]

In the third line I commented out what I tried and didn't work Is there a way to do this by swapping pointers instead...

unknown
  • 115
  • 4
  • What do you think `*tmp = *Z1` does? That copies ONE `int` to an undefined memory location as the compiler will warn you about. – Goswin von Brederlow May 31 '22 at 20:48
  • To swap pointers, you'll need to use pointers. If you have your heart set on swapping C-style arrays, a copy-to-swap of each element will have to be made. – Eljay May 31 '22 at 21:48

1 Answers1

9

how to swap arrays without copying elements

By virtue of what swapping is, and what arrays are, it isn't possible to swap arrays without copying elements (to be precise, std::swap swaps each element and a swap is conceptually a shallow copy).

What you can do is introduce a layer of indirection. Point to the arrays with pointers. Then, swapping the pointers will swap what arrays are being pointed without copying elements:

int* ptr1 = Z1;
int* ptr2 = Z2;
std::swap(ptr1, ptr2); // now ptr1 -> Z2, ptr2 -> Z1
eerorika
  • 232,697
  • 12
  • 197
  • 326
  • It was easier for me to try the second answer first. I have code involving Z1/Z2 before and after the swap so the second answer has less impact. I also see a speedup using it. Is there any advantage of using your solution over the second? – unknown May 31 '22 at 21:34
  • 1
    @unknown dynamic allocation, which Sedeion's answer does is slow. Bare owning pointers such as those in the other answer are error prone. You can name the array variable something else, and name the pointers as Z1,Z2 if that's a simpler change. – eerorika May 31 '22 at 21:39
  • thanks for the explanation. I tried your solution and it works too. – unknown May 31 '22 at 22:41