void *将具有与char指针相同的表示形式和内存对齐方式 [英] void* will have the same representation and memory alignment as a pointer to char

查看:124
本文介绍了void *将具有与char指针相同的表示形式和内存对齐方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在读一本有关理解并使用c指针"的指针的书.

I am reading a book on pointers named "understanding and using c pointers"

说到void *时说

它具有两个有趣的属性:

It has two interesting properties:

  1. 指向void的指针与指向char的指针具有相同的表示形式和内存对齐方式.

困惑的是所有指针的内存不一样吗?他们为什么不写void *与普通指针相同,而是显式提到char指针?非常感谢您的帮助

What am confused about is isn't the memory of all the pointers same? They why instead of writing void* is same as normal pointer it explicitly mentioned char pointers? Will really appreciate any help

推荐答案

在大多数常见的体系结构上,指向任何数据类型的指针都具有相同的表示形式,而指向函数的指针可能有所不同.但是,这不是必需的,因此可以创建有效的C实现,该实现对不同的数据类型使用不同的指针.其背后的原因是C标准倾向于仅描述关键要求,从而为可能的实现留出了很大的自由度.标准是这样的:

On most common architectures, pointer to any data type has the same representation, while pointer to function may differ. However, it's not a requirement, so it's possible to create valid C implementation, which uses different pointers for different data types. The reason behind this is that C standard tends to describe only crucial requirements, leaving a lot of freedom for possible implementations. Here is what standard says:

指向 void 的指针应具有与 指向字符类型的指针. 同样,指向合格或不合格版本的指针 兼容类型应具有相同的表示和对齐要求.全部 指向结构类型的指针应具有相同的表示和对齐要求 彼此.所有指向联合类型的指针都应具有相同的表示形式,并且 彼此之间的对齐要求.指向其他类型的指针不必具有相同的指针 表示或对齐要求.

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.

如果您想查看针对不同数据类型具有不同大小的系统的示例,请这些精彩例子

If you're curious to see examples of systems with different sizes for different data types, this question mentions these wonderful examples

这篇关于void *将具有与char指针相同的表示形式和内存对齐方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆