Swapping objects using pointers

后端 未结 10 1352
轻奢々
轻奢々 2020-12-03 18:20

I\'m trying to swap objects for a homework problem that uses void pointers to swap objects. The declaration of my function has to be:

void swap(void *a, voi         


        
10条回答
  •  盖世英雄少女心
    2020-12-03 18:25

    You're close.

    The problem is: you are "swapping" only pointers a and b which are local variables in the function.

    I assume outside of the function you have some variables, let's call them:

    void *x = ...;
    void *y = ...;
    

    When you call:

    swap(x, y, some_size);
    

    a and b points to the same objects as x and y respectively. Now, when you swap what a and b points too, x and y are still pointing to what they where pointing before.

    To change what memory x and y points you would have to pass a pointer to the x variable, so a pointer to a pointer :)

    Because you can't change function declaration you can only swap the content of the memory where x (and a) and y (and b) points to. Some solutions are in other answers :) Generally memcpy is what you want.

提交回复
热议问题