4

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.

asked Mar 11, 2010 at 12:41

3 Answers 3

7

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.

answered Mar 11, 2010 at 12:42
Sign up to request clarification or add additional context in comments.

Comments

5

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.

answered Mar 11, 2010 at 12:44

Comments

1

Beside the answer of AndreyT:

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

answered Mar 11, 2010 at 12:44

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.