I have a swap function like so:
void swap(int i, int j, void* arr[])
{
void *temp;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
I call swap in main like so:
main()
{
int arr[8] = {4,7,9,2,6,7,8,1};
void *ptr = arr;
swap(0, 1, ptr);
int k;
for (k=0; k<8; k++)
printf("%d ", arr[k]);
}
Now, the swap seems to work fine, however instead of swapping 1 value with another, it is swapping 2 values with another 2 values. For example, when I do swap(0, 1, ptr), i get the array
9,2,4,7,6,7,8,1
when I should be getting:
7,4,9,2,6,7,8,1
Instead of swapping 4 and 7, it is swapping 4,7 with 9,2. Why is it doing this?
swap()is treating the array as an array of pointers, but the actual array being passed is an array of typeint. Apparently, your system is such that a pointer is the size of twoints, and so everytime it swaps a “pointer”, it’s really swapping two integers.You would need your swap routine to be something like this: