gpt4 book ai didi

c - C 中的堆分配

转载 作者:太空宇宙 更新时间:2023-11-04 06:50:20 25 4
gpt4 key购买 nike

据我了解,您可以使用相同的变量名重新分配一个堆,它会在空间的不同位置分配内存。

但是,在这个例子中,我在我的第二个 malloc 中为指针变量 x 获得了相同的内存地址。有什么想法吗?

void main()
{
int *x = (int*)malloc(sizeof(int)); //allocate space for int value
*x = 100; //dereference x for value
printf("The value of x is %i address is %p\n",*x, &x);

int *y = (int*)malloc(sizeof(int)); //allocate space for int value
*y = 150; //dereference x for value
printf("The value of y is %i address is %p\n",*y, &y);

x = (int*)malloc(sizeof(int)); //allocate space for int value
*x = 400; //dereference x for value
printf("The value of x is %i address is %p\n",*x, &x);
}

gcc 给我这个:

The value of x is 100 address is 0xffffcc08
The value of y is 150 address is 0xffffcc00
The value of x is 400 address is 0xffffcc08

最佳答案

printf("The value of x is %i address is %p\n",*x, &x);

&x 这里它给出了变量 x 的地址,而不是它指向的内容。要获取它指向的地址,请使用以下内容:

printf("The value of x is %i address is %p\n",*x, (void *)x)

关于c - C 中的堆分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52480686/

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