Pointer arithmetic for void pointer in C

前端 未结 8 1211
执念已碎
执念已碎 2020-11-22 01:23

When a pointer to a particular type (say int, char, float, ..) is incremented, its value is increased by the size of that data type. I

8条回答
  •  滥情空心
    2020-11-22 01:50

    Void pointers can point to any memory chunk. Hence the compiler does not know how many bytes to increment/decrement when we attempt pointer arithmetic on a void pointer. Therefore void pointers must be first typecast to a known type before they can be involved in any pointer arithmetic.

    void *p = malloc(sizeof(char)*10);
    p++; //compiler does how many where to pint the pointer after this increment operation
    
    char * c = (char *)p;
    c++;  // compiler will increment the c by 1, since size of char is 1 byte.
    

提交回复
热议问题