In this code:
int a[10];
int b[10];
int *aux;
aux=a;
a=b;
b=aux;
The statement aux=a;
works because a
decays into a pointer to its 1st element. So this is effectively just the same as aux=&a[0];
The statement a=b;
does not work because a
and b
are both arrays, and arrays are simply not copyable in this manner. You are trying to do &a[0]=&b[0];
and that simply will not work. You can't reassign a variable's address in memory.
Had you used std::array
instead, then the statement a=b;
would work, as std::array
has an operator=
implemented, which simply copies each element from one array to another. But if you are not using std::array
, then you have to copy the elements manually, using memcpy()
or better std::copy()
.
The statement b=aux;
does not work because b
is an array and aux
is a pointer, and you can't assign a pointer to an array.
For what you are attempting to do, you will have to change aux
into an array, and actually copy the elements from one array to another, eg:
#include <algorithm>
int a[10];
int b[10];
int aux[10];
std::copy(a, a+10, aux);
std::copy(b, b+10, a);
std::copy(aux, aux+10, b);
Or, using std::array
, which can do the copy for you:
#include <array>
std::array<int, 10> a;
std::array<int, 10> b;
std::array<int, 10> aux;
aux = a;
a = b;
b = aux;
Whereas in the other code:
int *a=(int*)malloc(10);
int *b=(int*)malloc(10);
int *aux;
aux=a;
a=b;
b=aux;
You are just swapping around pointers of the same type (int*
), it doesn't matter what they are actually pointing at, you are not touching that data. And BTW, (int*)malloc(10)
is wrong for an int
array, it would need to be (int*)malloc(sizeof(int)*10)
instead.