Swapping objects using pointers

后端 未结 10 1353
轻奢々
轻奢々 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:41

    To answer your first question, let's fill in some values to see what is happening:

    void* a = 0x00001000; // some memory address
    void* b = 0x00002000; // another memory address
    /* Now we'll put in your code */
    void* temp; // temp is garbage
    temp = a; // temp is now 0x00001000
    a = b; // a is now 0x00002000
    b = temp; // b is now 0x00001000
    

    So at the end of those statements, the pointer's values have been swapped, that is, whatever a was pointing to is now pointed to by b, and vice versa. The values of what those pointers are pointing to are unmodified, it's just that now their memory addresses are being held by different pointers.

    To answer your second question, you cannot dereference a void*. The reason for this is that void has no size, so to try and dereference or assign to something that has no size is nonsensical. Thus, void* is a way of guaranteeing you can point to something, but you will never know what that something is without more information (hence the size parameter to your routine).

    From there, knowing the pointer and the size of the data the pointer points to, you can use a routine like memcpy to move the data pointed to by one pointer into the location pointed to by another.

提交回复
热议问题