4
int main()  
{  
    int a;  
    void *p;  
    p = &a;  
    printf("%ld\n",(long)p);  
    p = p+1;  
    printf("%ld\n",(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.

William Pursell
  • 204,365
  • 48
  • 270
  • 300
RAM JI GUPTA
  • 47
  • 1
  • 6
  • 1
    What do you expect the result of dereferencing a void pointer to be?! – Kerrek SB Oct 28 '12 at 21:44
  • Also, what's the question? You already noticed that GCC implements void pointer arithmetic like char pointer arithmetic, so what exactly is unclear? – Kerrek SB Oct 28 '12 at 21:45

1 Answers1

10

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.

ouah
  • 142,963
  • 15
  • 272
  • 331
  • then why dereferencing is not allowed in GNU C? – RAM JI GUPTA Oct 28 '12 at 21:48
  • As far as GCC is concerned, when we write just *p this statement is removed as a part of optimization step. So actually dereferencing does not take place..If i write int x = *p; then it gives an error – RAM JI GUPTA Oct 28 '12 at 22:05
  • 1
    The real reason why you cannot dereference a `void *` actually involves lvalues, `void` is an incomplete type and lvalues cannot have an incomplete type. – ouah Oct 28 '12 at 23:03