gpt4 book ai didi

c++ - 内存中变量之间的距离

转载 作者:行者123 更新时间:2023-11-30 02:41:25 25 4
gpt4 key购买 nike

我想知道 C++ 是如何处理变量的,以便一个接一个地声明和初始化的整数变量在内存中的两个地址之间的距离是 3537492 - 3537480 = 12(我假设位(?))

#include <cstdio>

using namespace std;

int main( int argc, char ** argv )
{
int x = 1;
int y = 2;

printf("int:\t%d\n", sizeof(int));
printf("unsigned int:\t%d\n", sizeof(unsigned int));

printf("Address of x\n\tHex:\t%p\n\tDec:\t%d\n", &x, &x);
printf("Address of y\n\tHex:\t%p\n\tDec:\t%d\n", &y, &y);

return 0;
}

输出:

int:    4unsigned int:   4Address of x        Hex:    0035FA54        Dec:    3537492Address of y        Hex:    0035FA48        Dec:    3537480

最佳答案

我的猜测是编译器出于某些性能原因将整数沿字边界对齐。如果一个字是 128 位或 16 个字节,那么这种行为将导致变量之间有 12 个字节的距离。您必须更多地了解您正在编译的架构才能知道我是否正确。没有双关语的意思。参见 http://en.wikipedia.org/wiki/Data_structure_alignment

关于c++ - 内存中变量之间的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28161381/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com