C - Dereferencing void pointer

前端 未结 5 583
独厮守ぢ
独厮守ぢ 2021-01-28 15:51

I\'m trying to create my own swap function but I have troubles.
Why I\'m getting \" dereferencing void pointer \" ?

void    ft_swap(void *a, void *b, size         


        
5条回答
  •  忘了有多久
    2021-01-28 16:37

        cur_a = (unsigned char *)*a + i; // here
                                 ^^^ that is dereferencing a void*
    
        cur_b = (unsigned char *)*b + i; // here
                                 ^^^ that is dereferencing a void* also.
    

    In the lines:

        *a = cur_b;
        *b = cur_a;
    

    you are dereferencing void* too.

    Here's my suggestion to fix the function:

    void ft_swap(void *a, void *b, size_t nbytes)
    {
       unsigned char* cpa;
       unsigned char* cpb;
       size_t          i;
       unsigned char c;
    
       cpa = (unsigned char *)a;
       cpb = (unsigned char *)b;
    
       for ( i = 0; i < nbytes; ++i )
       {
          c = cpa[i];
          cpa[i] = cpb[i];
          cpb[i] = c;
       }
    }
    

提交回复
热议问题