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


当前回答

即使是在普通的x86 32位平台上,你也可以得到不同大小的指针,试试这个例子:

struct A {};

struct B : virtual public A {};

struct C {};

struct D : public A, public C {};

int main()
{
    cout << "A:" << sizeof(void (A::*)()) << endl;
    cout << "B:" << sizeof(void (B::*)()) << endl;
    cout << "D:" << sizeof(void (D::*)()) << endl;
}

在Visual c++ 2008中,指向成员函数的指针的大小分别为4、12和8。

Raymond Chen在这里讲过。

其他回答

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

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

指针只是一个地址的容器。在32位计算机上,您的地址范围是32位,因此指针总是4字节。在64位机器上,如果你的地址范围是64位,一个指针将是8字节。

The size of the pointer basically depends on the architecture of the system in which it is implemented. For example the size of a pointer in 32 bit is 4 bytes (32 bit ) and 8 bytes(64 bit ) in a 64 bit machines. The bit types in a machine are nothing but memory address, that it can have. 32 bit machines can have 2^32 address space and 64 bit machines can have upto 2^64 address spaces. So a pointer (variable which points to a memory location) should be able to point to any of the memory address (2^32 for 32 bit and 2^64 for 64 bit) that a machines holds.

由于这个原因,我们看到指针的大小在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.

指针大小为4字节的原因是因为您正在为32位体系结构编译。正如FryGuy所指出的,在64位架构上你将看到8。