C - Dereferencing void pointer

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

    Because you are dereferencing void pointers:

    void    ft_swap(void *a, void *b, size_t nbytes)
    {
     ...
            cur_a = (unsigned char *)*a + i; // here
            cur_b = (unsigned char *)*b + i; // here
    

    Doing *a means you first dereference a, and then you cast the result (whatever that is, dereferencing void* doesn't make much sense) to a pointer to unsigned char. Doing

    cur_a = *((unsigned char *)a) + i;
    

    makes more sense.

提交回复
热议问题