问题描述
指针的大小是否与其所指向的类型的大小相同,还是指针始终具有固定的大小?例如...
Is the size of a pointer the same as the size as the type its pointing to, or do pointers always have a fixed size? For example...
int x = 10;
int * xPtr = &x;
char y = 'a';
char * yPtr = &y;
std::cout << sizeof(x) << "\n";
std::cout << sizeof(xPtr) << "\n";
std::cout << sizeof(y) << "\n";
std::cout << sizeof(yPtr) << "\n";
这将是什么输出? sizeof(xPtr)
返回4,sizeof(yPtr)
返回1,还是2个指针实际上返回相同的大小?我之所以这样问,是因为指针存储的是内存地址,而不是它们各自存储的地址的值.
What would the output of this be? Would sizeof(xPtr)
return 4 and sizeof(yPtr)
return 1, or would the 2 pointers actually return the same size? The reason I ask this is because the pointers are storing a memory address and not the values of their respective stored addresses.
推荐答案
指针通常具有固定的大小,例如.在32位可执行文件上,它们通常是32位.有一些例外,例如在旧的16位窗口上,当您必须区分32位指针和16位...时,通常很安全的假设它们在现代桌面操作系统的给定可执行文件中将是统一的
Pointers generally have a fixed size, for ex. on a 32-bit executable they're usually 32-bit. There are some exceptions, like on old 16-bit windows when you had to distinguish between 32-bit pointers and 16-bit... It's usually pretty safe to assume they're going to be uniform within a given executable on modern desktop OS's.
即使这样,我也强烈警告不要在您的代码中做这个假设.如果您要编写绝对必须具有一定大小的指针的东西,则最好检查一下!
Even so, I would strongly caution against making this assumption in your code. If you're going to write something that absolutely has to have a pointers of a certain size, you'd better check it!
函数指针是另一回事-有关详细信息,请参见 Jens的答案.
Function pointers are a different story -- see Jens' answer for more info.
这篇关于指针的大小是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!