gpt4 book ai didi

c - 变量的地址低于指针的地址?

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

int main(int argc  , char *argv[] ) 
{
int value = 5;
char buffer_one[8] , buffer_two[8];

strcpy(buffer_one,"one");
strcpy(buffer_two,"two");
printf("[BEFORE] buffer_two is at %p and containt \'%s\' \n ",buffer_two,buffer_two);

printf("[BEFORE] buffer_one is at %p and containt \'%s\' \n ",buffer_one,buffer_one);
printf("[BEFORE] value is at %p and is %d (0x%08x)\n",&value,value,value);
}

我得到了这个结果:

[BEFORE] buffer_two is at 0x7ffd75d46720 and containt 'two' 
[BEFORE] buffer_one is at 0x7ffd75d46710 and containt 'one'
[BEFORE] value is at 0x7ffd75d4670c and is 5 (0x00000005)

正如您所看到的,buffer_two 的地址高于 buffer_one (因为它被推送到堆上,并且堆上升到更高的地址),这里一切正常。

我不明白为什么Value变量的地址比两者都小,我认为它一定更高,因为变量存储在堆栈上!并且栈的地址比堆高!

最佳答案

因为所有三个变量都是在函数内定义的,所以它们都位于堆栈中。堆栈通常向下增长,因此看起来 buffer_two 的空间首先被插入堆栈,然后是 8 个填充字节,然后是 buffer_one,最后是 value .

话虽这么说,变量如何放置在堆栈上是实现定义的,并且当进行看似不相关的代码更改时,在同一实现中可能会有所不同。

例如,在我的系统上,此代码输出以下内容:

[BEFORE] buffer_two is at 0xbfb16110 and containt 'two' 
[BEFORE] buffer_one is at 0xbfb16118 and containt 'one'
[BEFORE] value is at 0xbfb16120 and is 5 (0x00000005)

在这种情况下,变量以相反的顺序放置在堆栈上,并且没有 8 字节填充。

关于c - 变量的地址低于指针的地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33268605/

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