Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
710 views
in Technique[技术] by (71.8m points)

c - How void pointer arithmetic is happening in GCC

int main()  
{  
    int a;  
    void *p;  
    p = &a;  
    printf("%ld
",(long)p);  
    p = p+1;  
    printf("%ld
",(long)p);  
}  

In this program, p+1 is just incrementing the value of p by 1. I know void pointer arithmetic is not possible in C, so GCC is doing it implicitly. And if yes, then is it taking it as char pointer. Also, why dereferencing is not possible for void pointer, if it is implicitly doing pointer arithmetic.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

C does not allow pointer arithmetic with void * pointer type.

GNU C allows it by considering the size of void is 1.

From 6.23 Arithmetic on void- and Function-Pointers:

In GNU C, addition and subtraction operations are supported on pointers to void and on pointers to functions. This is done by treating the size of a void or of a function as 1.

http://gcc.gnu.org/onlinedocs/gcc/Pointer-Arith.html

Now to answer this question:

Also, why dereferencing is not possible for void pointer, if it is implicitly doing pointer arithmetic.

GNU C allows pointer arithmetic with void * but still does not allow an object of type void to be declared.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...