C - Dereferencing void pointer

前端 未结 5 533
独厮守ぢ
独厮守ぢ 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:34

    It's not allowed to dereference void pointer. You need to cast it to another pointer type:

    cur_a = (unsigned char *)a;
    

    Similarly, you can't assign anything to *a. Right code is:

    void ft_swap(void *a, void *b, size_t nbytes) {
        unsigned char  *cur_a = (unsigned char *) a;
        unsigned char  *cur_b = (unsigned char *) b;
    
        for (size_t i = 0; i < nbytes; ++i) {
            unsigned char tmp = cur_a[i];
            cur_a[i] = cur_b[i];
            cur_b[i] = tmp;
        }
    }
    

提交回复
热议问题