简体   繁体   中英

using void pointer in swap function

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 type int . Apparently, your system is such that a pointer is the size of two int s, and so everytime it swaps a "pointer", it's really swapping two integers.

You would need your swap routine to be something like this:

void swap(int i, int j, int arr[])
{
    int temp;
    temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM