void* 将具有与指向 char 的指针相同的表示和内存对齐方式
void* will have the same representation and memory alignment as a pointer to char
我正在阅读一本关于指针的书,名为“理解和使用 C 指针”
当谈到 void *
时,它说
It has two interesting properties:
- A pointer to void will have the same representation and memory alignment as a pointer to char.
疑惑的是不是所有指针的内存都是一样的吗?他们为什么不写 void* is same as normal pointer 而不是明确提到 char 指针?非常感谢任何帮助
在大多数常见的体系结构中,指向任何数据类型的指针具有相同的表示形式,而指向函数的指针可能不同。但是,这不是必需的,因此可以创建有效的 C 实现,它对不同的数据类型使用不同的指针。这背后的原因是 C 标准倾向于只描述关键要求,为可能的实现留下很多自由。这是标准所说的:
A pointer to void shall have the same representation and alignment requirements as a
pointer to a character type.
Similarly, pointers to qualified or unqualified versions of
compatible types shall have the same representation and alignment requirements. All
pointers to structure types shall have the same representation and alignment requirements
as each other. All pointers to union types shall have the same representation and
alignment requirements as each other. Pointers to other types need not have the same
representation or alignment requirements.
如果您想查看针对不同数据类型使用不同大小的系统示例,this question mentions these wonderful examples
我认为这里的重点是"memory alignment",而不是"memory size"。
是的,所有指针都具有相同大小的内存。但它们可能对内存对齐有不同的限制。
例如,在一些平台上,一个“32-bit int”指针必须指向地址,该地址应该是4字节的倍数。它不能指向,例如0x100001 或 0x100003。
但是“8 位字符”指针可以指向任何地址。 "void" 指针也是如此。
是这么说的
我正在阅读一本关于指针的书,名为“理解和使用 C 指针”
当谈到 void *
时,它说
It has two interesting properties:
- A pointer to void will have the same representation and memory alignment as a pointer to char.
疑惑的是不是所有指针的内存都是一样的吗?他们为什么不写 void* is same as normal pointer 而不是明确提到 char 指针?非常感谢任何帮助
在大多数常见的体系结构中,指向任何数据类型的指针具有相同的表示形式,而指向函数的指针可能不同。但是,这不是必需的,因此可以创建有效的 C 实现,它对不同的数据类型使用不同的指针。这背后的原因是 C 标准倾向于只描述关键要求,为可能的实现留下很多自由。这是标准所说的:
A pointer to void shall have the same representation and alignment requirements as a pointer to a character type. Similarly, pointers to qualified or unqualified versions of compatible types shall have the same representation and alignment requirements. All pointers to structure types shall have the same representation and alignment requirements as each other. All pointers to union types shall have the same representation and alignment requirements as each other. Pointers to other types need not have the same representation or alignment requirements.
如果您想查看针对不同数据类型使用不同大小的系统示例,this question mentions these wonderful examples
我认为这里的重点是"memory alignment",而不是"memory size"。
是的,所有指针都具有相同大小的内存。但它们可能对内存对齐有不同的限制。
例如,在一些平台上,一个“32-bit int”指针必须指向地址,该地址应该是4字节的倍数。它不能指向,例如0x100001 或 0x100003。
但是“8 位字符”指针可以指向任何地址。 "void" 指针也是如此。
是这么说的