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.
3 Answers 3
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.
Comments
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.