Swapping objects using pointers

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

    Swapping pointers does not change the pointed-to values. If it did, that would be like swapping address labels on envelopes moving me into your house and you into mine.

    You were nearly there:

    void swap(void *a, void *b, size_t size) {
      char temp[size]; // C99, use malloc otherwise
      // char serves as the type for "generic" byte arrays
    
      memcpy(temp, b,    size);
      memcpy(b,    a,    size);
      memcpy(a,    temp, size);
    }
    

    The memcpy function copies memory, which is the definition of objects in C. (Called POD or plain ol' data in C++, to compare.) In this way, memcpy is how you do assignment without caring about the type of the object, and you could even write other assignments as memcpy instead:

    int a = 42, b = 3, temp;
    
    temp = b;
    b    = a;
    a    = temp;
    // same as:
    memcpy(&temp, &b,    sizeof a);
    memcpy(&b,    &a,    sizeof a);
    memcpy(&a,    &temp, sizeof a);
    

    This is exactly what the above function does, since you cannot use assignment when you do not know the type of the object, and void is the type that stands in for "unknown". (It also means "nothing" when used as function return type.)


    As a curiosity, another version which avoids malloc in common cases and doesn't use C99's VLAs:

    void swap(void *a, void *b, size_t size) {
      enum { threshold = 100 };
      if (size <= threshold) {
        char temp[threshold];
    
        memcpy(temp, b,    size);
        memcpy(b,    a,    size);
        memcpy(a,    temp, size);
      }
      else {
        void* temp = malloc(size);
        assert(temp); // better error checking desired in non-example code
    
        memcpy(temp, b,    size);
        memcpy(b,    a,    size);
        memcpy(a,    temp, size);
    
        free(temp);
      }
    }
    

提交回复
热议问题