开发者

Portability of a C code

I have the following code

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

D开发者_如何学编程oes 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.


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.


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.


Beside the answer of AndreyT:

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜