sizeof(void) 在 C 中等于 1? [英] sizeof(void) equals 1 in C?
问题描述
可能的重复:
void 的大小是多少?
大家好!我正在使用 gcc 来编译我的 C 程序,只是偶然发现在 C 中 sizeof(void) 是 1 个字节.
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) !
谢谢!
推荐答案
这是 gcc 的非标准扩展,但有其基本原理.当您进行指针算术添加或删除一个单位时,意味着添加或删除指向大小的对象.因此,将 sizeof(void)
定义为 1 有助于将 void*
定义为指向字节(无类型内存地址)的指针.否则,当 p 为 void*
时,您会使用诸如 p+1 == p
之类的指针算术出现令人惊讶的行为.
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*
.
标准方法是将 `char* 用于这种目的(指向字节的指针).
The standard way would be to use `char* for that kind of purpose (pointer to byte).
这篇关于sizeof(void) 在 C 中等于 1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!