void * arithmetic

前端 未结 5 2201
说谎
说谎 2020-12-16 11:39
#include
int main(int argc,char *argv[])
{
   int i=10;
   void *k;
   k=&i;

   k++;
   printf(\"%p\\n%p\\n\",&i,k);
   return 0;
}
         


        
5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-16 11:56

    Arithmetic on void* is a GCC extension. When I compile your code with clang -Wpointer-arith the output is :

    test.c:9:4: warning: use of GNU void* extension [-Wpointer-arith]
    k++;
    ~^
    

    The usual behavior of a pointer increment is to add the size of the pointee type to the pointer value. For instance :

    
    int *p;
    char *p2;
    p++; /* adds sizeof(int) to p */
    p2 += 2; /* adds 2 * sizeof(char) to p2 */

    Since void has no size, you shouldn't be able to perform pointer arithmetic on void* pointers, but GNU C allows it.

提交回复
热议问题