sizeof(void) equals 1 in C? [duplicate]

耗尽温柔 提交于 2019-11-30 15:46:37

问题


Possible Duplicate:
What is the size of void?

Hi all ! I am using gcc for compiling my C programs, just discovered accidentally that the sizeof(void) is 1 byte in C.

Is there any explanation for this ? I always thought it to be ZERO (if it really stores nothing) !

Thanks !


回答1:


This is a non standard extension of gcc, but has a rationale. When you do pointer arithmetic adding or removing one unit means adding or removing the object pointed to size. Thus defining sizeof(void) as 1 helps defining void* as a pointer to byte (untyped memory address). Otherwise you would have surprising behaviors using pointer arithmetic like p+1 == p when p is void*.

The standard way would be to use `char* for that kind of purpose (pointer to byte).




回答2:


this is a gcc specific feature - see here http://gcc.gnu.org/onlinedocs/gcc-4.4.2/gcc/Pointer-Arith.html#Pointer-Arith

or

What is the size of void?




回答3:


Usually you don't ask for sizeof(void) since you never use void as type. I guess the behavior you are experimenting depends on the specific compiler. On my gcc it returns 1 as well.



来源:https://stackoverflow.com/questions/3350599/sizeofvoid-equals-1-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!