简体   繁体   中英

How to correctly swap void pointers?

I have a task:
I need to swap an elements in array, by "void pointers based" swap function. Its a simple bubble sort algorithm.
But my void SwapInt(void *x, void *y) function doesnt work, I mean it called correctly. but did nothing. My pre-sorting array doesnt change? What could be wrong here and how it fix?

void SwapInt(void *x, void *y)
{
    void *buffer = x;
    x = y;
    y = buffer;
}

bool CmpInt(void *x, void *y)
{
    int *intPtrX = static_cast<int*>(x);
    int *intPtrY = static_cast<int*>(y);
    if(*intPtrX > *intPtrY)
        return true;
    else
        return false;
}

void Sort(int array[], int nTotal, size_t size, void (*ptrSwapInt)(void *x, void *y), bool (*ptrCmpInt)(void *x, void *y))
{
    for (int i = 0; i < nTotal; i++)
    {
        for (int j = 0; j < nTotal - 1; j++)
        {
          if (ptrCmpInt(&array[j] , &array[j + 1]))
          {
            ptrSwapInt(&array[j], &array[j + 1]);
          }
        }
    }
}

PS I have already visit StackOverflow_1 and StackOverflow_2 , and I still dont have a clue, what is wrong.

You can't swap integers by swapping pointers, you have to dereference the pointers. And to do that you have to cast them to the int pointers that they really are.

void SwapInt(void *x, void *y)
{
    int temp = *static_cast<int*>(x);
    *static_cast<int*>(x) = *static_cast<int*>(y);
    *static_cast<int*>(y) = temp;
}

In fact you did this perfectly correctly in your CmpInt function, so I'm not sure what the problem in SwapInt was.

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