Swapping objects using pointers

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

    To change the pointer inside and keep it outside, you have to pass the pointer by reference or a double pointer.

    If your function has to be like:

    void swap(void *a, void *b, size_t size);
    

    I suppose that you have to implement something like:

    void * temp;
    temp = malloc(size);
    memcpy(temp,a,size);
    memcpy(a,b,size);
    memcpy(b,temp,size);
    free(temp);
    

提交回复
热议问题