gpt4 book ai didi

c++ - 指针内存分配

转载 作者:太空狗 更新时间:2023-10-29 19:48:16 25 4
gpt4 key购买 nike

我正在尝试深入学习指针的概念。在下面的代码中,我创建了一个数组并创建了一个指向每个元素的指针。

int bucky[5];
int *bp0 = &bucky[0];
int *bp1 = &bucky[1];
int *bp2 = &bucky[2];

cout<<"bp0 is at memory address:"<<bp0<<endl;
cout<<"bp1 is at memory address:"<<bp1<<endl;
cout<<"bp2 is at memory address:"<<bp2<<endl;

这些是分配给数组元素的内存。

bp0 is at memory address:0x0018ff3c
bp1 is at memory address:0x0018ff40
bp2 is at memory address:0x0018ff44

以我对 c++ 的有限了解,我知道内存是连续分配给数组的。但仔细观察输出,bp0 看起来不合适。

根据我的说法,bp0 应该位于 0x0018ff36。还是位置 0x0018ff3c , 0x0018ff40 , 0x0018ff44 在 CPU 中是连续的?

那么有没有可能两个连续的内存分配没有按顺序分配?

最佳答案

           +---+---+---+---+---+---+---+---+---+---+---+---+
| bp0 | bp1 | bp2 |
+---+---+---+---+---+---+---+---+---+---+---+---+
0x0018ff3c d e f 40 1 2 3 4 5 6 7 8

假设 int 的大小是 4 个字节并且 bp0 指向 0x0018ff3c。

bp1 = bp0 + 4 = 0x0018ff40
bp2 = bp1 + 4 = 0x0018ff44

关于c++ - 指针内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28626657/

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