C - Dereferencing void pointer

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

    Look your statement

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

    if a is a pointer to void (void *a) then *a = void. Then the subexpression (unsigned char *)*a means that you want to cast void to a pointer to char.

    But void means 'inexistent type' in C, from this the error. You may ask why a pointer to void make sense instead, it makes sense because it is an address, that is a valid data type in C. You can use the address for all the operations that doesn't involve the pointed type. I.e. assigning the address to a pointer to whichever type of data, and the reverse, is legal. It's is illegal an expression like a[2] where the subscript operator [] need the size of the data pointed to compute the address where to retrieve the value. Of course void, as bogus type, have no size (same way as it miss many other properties).

    Said that I would conclude that it was just an error in your code, and that what you really want to do is:

    void    ft_swap(void *a, void *b, size_t nbytes)
    {
        unsigned char   cur_a;    //value not pointers
        unsigned char   cur_b;
        size_t          i;
    
        i = 0;
        while (i < nbytes)
        {
            cur_a = *((unsigned char *)a + i); // here
            cur_b = *((unsigned char *)b + i); // here
    
            *a = cur_b;
            *b = cur_a;
    
            i++;
        }
    }
    

提交回复
热议问题