For educational purposes, I was trying to swap two integer arrays with their memory locations using array pointers but I came across some weird problem and I can't figure out why this is happening,
so when I tried to create an int array and swapped their locations using swap function below, only half of their elements changed but when I switched int fArr[size];
to int *fArr = malloc(sizeof(int) * size);
it works perfectly fine.
Why this is happening and can casting from &int[]
to int **
cause a problem?
int main(void) {
...
int fArr[size];
int sArr[size];
initArr(fArr, sArr, size);
...
swapArr((int **)&fArr, (int **)&sArr, size);
}
void initArr(int fArr[], int sArr[], size_t size) {
srand(time(NULL));
for (size_t i = 0; i < size; i ) {
fArr[i] = rand() % 1000;
sArr[i] = rand() % 1000;
}
}
void swapArr(int **fArr, int **sArr, size_t size) {
int *temp = *fArr;
*fArr = *sArr;
*sArr = temp;
}
and output of this complete code is
Array : 0x7ffcdb611cf0
521, 210, 426, 263
Array : 0x7ffcdb611ce0
553, 314, 17, 16
------- After Swap -------
Array : 0x7ffcdb611cf0
553, 314, 426, 263
Array : 0x7ffcdb611ce0
521, 210, 17, 16
CodePudding user response:
The function swapArr
swaps the values of 2 pointers. You pass the addresses of int
arrays, inappropriately cast as pointers to int *
. The code has undefined behavior. What is happening is the first 2 entries of the arrays are swapped because int *
on your architecture happens to have the size of 2 int
: for example int *
on a 64-bit CPU has 8 bytes while int
is a 32-bit type occupying 4 bytes.
Note that the arguments to initArrays
are really int *
despite the declaration syntax void initArr(int fArr[], int sArr[], size_t size)
. When you pass an array as a function argument (and most other expression contexts) it decays as a pointer to its first element.
To swap the array contents, you need to use a loop:
void swapArr(int *fArr, int *sArr, size_t size) {
for (size_t i = 0; i < size; i ) {
int temp = fArr[i];
fArr[i] = sArr[i];
sArr[i] = temp;
}
}