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


当前回答

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

其他回答

只是已经发布的列表中的另一个例外。在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位段值组成

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

从技术上讲,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.

在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。

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