1

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]);
          }
        }
    }
}

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

  • You know there's a standard `std::swap` function that works very well, right? Why is your `SwapInt` taking two `void*` btw? Two `int&` would seem more appropriate. – Ted Lyngmo Feb 21 '21 at 21:06
  • You need a pointer or reference to those pointers if you want to affect them outside the function. – Mark Ransom Feb 21 '21 at 21:07
  • 1
    You change local variables, to change what is passed, use `void SwapInt(void **x, void **y)` or `void SwapInt(void *&x, void *&y)` – Suthiro Feb 21 '21 at 21:09
  • Do you want to swap the pointers themselves or do you want to swap the things they point to? If `x` points to `1` and `y` points to `2`, do you want to swap the `1` and the `2` so `x` still points to the same place but that place now contains a `2`? Or do you want to swap `x` and `y` so `x` now points to a different place but that place still contains the same `2` it contained before? – David Schwartz Feb 21 '21 at 21:58

1 Answers1

1

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.

john
  • 85,011
  • 4
  • 57
  • 81
  • Its helped! I thought about it, but in my opinion it was like "bad style" . Now I see, that I wasn`t right. Thank you very much! – Nikita Albekov Feb 21 '21 at 21:19
  • 1
    Well the whole exercise is bad style. It's the kind of coding you would do in C not C++ (but I realise that this isn't your choice). – john Feb 21 '21 at 21:20