例如: Sizeof (char*)返回4。还有int* long long*,我试过的所有方法。有什么例外吗?


当前回答

据我所知,这是基于内存地址的大小。所以在一个32位地址方案的系统上,sizeof将返回4,因为那是4个字节。

其他回答

除了人们所说的64位(或其他)系统,还有其他类型的指针,而不是指向对象的指针。

指向成员的指针几乎可以是任何大小,这取决于编译器如何实现它们:它们甚至不一定都是相同的大小。尝试一个POD类的指向成员的指针,然后尝试一个继承自具有多个基类的基类之一的指向成员的指针。什么乐趣。

你得到的保证是sizeof(char) == 1。没有其他保证,包括没有保证sizeof(int *) == sizeof(double *)。

在实践中,指针的大小在16位系统上为2(如果您能找到一个),在32位系统上为4,在64位系统上为8,但是依赖于给定的大小并不能获得任何东西。

从技术上讲,C标准只保证sizeof(char) == 1,其余的取决于实现。但在现代x86架构(例如Intel/AMD芯片)上,这是相当可预测的。

You've probably heard processors described as being 16-bit, 32-bit, 64-bit, etc. This usually means that the processor uses N-bits for integers. Since pointers store memory addresses, and memory addresses are integers, this effectively tells you how many bits are going to be used for pointers. sizeof is usually measured in bytes, so code compiled for 32-bit processors will report the size of pointers to be 4 (32 bits / 8 bits per byte), and code for 64-bit processors will report the size of pointers to be 8 (64 bits / 8 bits per byte). This is where the limitation of 4GB of RAM for 32-bit processors comes from -- if each memory address corresponds to a byte, to address more memory you need integers larger than 32-bits.

不,指针的大小可能因架构而异。有很多例外。

除了16位/32位/64位的差异之外,还会发生更奇怪的事情。

曾经有一些机器sizeof(int *)是一个值,可能是4,但sizeof(char *)更大。自然地处理单词而不是字节的机器必须“增加”字符指针,以指定您真正想要的单词的哪一部分,以便正确地实现C/ c++标准。

现在这是非常不寻常的,因为硬件设计师已经了解了字节可寻址性的价值。