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


当前回答

在Win64 (Cygwin GCC 5.4)中,让我们看看下面的例子:

首先,测试下面的结构:

struct list_node{
    int a;
    list_node* prev;
    list_node* next;
};

struct test_struc{
    char a, b;
};

测试代码如下:

std::cout<<"sizeof(int):            "<<sizeof(int)<<std::endl;
std::cout<<"sizeof(int*):           "<<sizeof(int*)<<std::endl;
std::cout<<std::endl;

std::cout<<"sizeof(double):         "<<sizeof(double)<<std::endl;
std::cout<<"sizeof(double*):        "<<sizeof(double*)<<std::endl;
std::cout<<std::endl;

std::cout<<"sizeof(list_node):      "<<sizeof(list_node)<<std::endl;
std::cout<<"sizeof(list_node*):     "<<sizeof(list_node*)<<std::endl;
std::cout<<std::endl;

std::cout<<"sizeof(test_struc):     "<<sizeof(test_struc)<<std::endl;
std::cout<<"sizeof(test_struc*):    "<<sizeof(test_struc*)<<std::endl;    

输出如下:

sizeof(int):            4
sizeof(int*):           8

sizeof(double):         8
sizeof(double*):        8

sizeof(list_node):      24
sizeof(list_node*):     8

sizeof(test_struc):     2
sizeof(test_struc*):    8

你可以看到在64位中,sizeof(指针)是8。

其他回答

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

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

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

一般来说,当你在不同的平台上编译时,sizeof(几乎任何东西)都会改变。在32位平台上,指针的大小总是相同的。在其他平台上(64位是最明显的例子),这种情况可能会发生变化。

只是已经发布的列表中的另一个例外。在32位平台上,指针可以占用6字节,而不是4字节:

#include <stdio.h>
#include <stdlib.h>

int main() {
    char far* ptr; // note that this is a far pointer
    printf( "%d\n", sizeof( ptr));
    return EXIT_SUCCESS;
}

如果你用Open Watcom编译这个程序并运行它,你会得到6,因为它支持的远指针由32位偏移量和16位段值组成

即使是在普通的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在这里讲过。