tags:

views:

105

answers:

3

I have the following code

int main()
{
   int a=6;
   void *p;
   p=&a;
   p++;
}

Does the void pointer here increment by a particular value (if it is holding the address of any data type) ?

In the above case p increments by 1 even though it is pointing to an integer value. According to me the above code invokes Implementation Defined behavior.

+7  A: 

The code in not valid from standard C point of view. It is illegal to increment void * pointers, or any other pointers to incomplete types.

Your compiler implements it as an extension, which is, of course, non-portable.

AndreyT
Thanks for the answer. :)
CadetNumber1
+5  A: 

Applying the ++ operator to void* is a GCC extension, which I'm told makes certain things a bit more convenient for very low-level programming (not having to cast so much, basically). I don't think I've ever hit a situation where I seriously don't want to cast to unsigned char*.

Use the -pedantic flag if you're writing code that's supposed to be portable.

Steve Jessop
+1 for the pedantic flag
Macmade
+1  A: 

Beside the answer of AndreyT:

Have a look at stdint.h which makes your code more portable.

tanascius