C打印数组指针地址问题

C print address of pointer to array problem

当我运行以下代码时:

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int array[100];
    int (*array_ptr)[100];
    void *buff = malloc(500);
    int *ptr;
    printf("array: %p \narray+1: %p\n", array, array+1);
    printf("array_ptr: %p \narray_ptr+1: %p\n", array_ptr, array_ptr+1);
    printf("buff: %p\n", buff);
    printf("ptr: %p\n", ptr);
}

结果是这样的:

array: 0x7fffe6dc6bd0
array+1: 0x7fffe6dc6bd4
array_ptr: (nil)
array_ptr+1: 0x190
buff: 0x1f80260
ptr: 0x7fffe6dd417c

我运行它多次,arrayarray+1buffptr都是随机改变值,但是array_ptrarray_prt+1 永远不会改变,尽管指针运算结果 0x190 符合预期。

是否表明array_ptr指向的数组存储在堆中?但是 buff 指向的动态分配的内存块也应该在堆中并且它的值发生变化,这是为什么?谢谢!

Does it indicate that the array pointed by array_ptr is stored in heap?

没有。 array_ptr 指向任何内容,既不在堆栈上也不在堆上。


int (*array_ptr)[100];

array_ptrone 指向 100 int 个对象的数组的指针,但是使用此语句您不会创建包含 100 [=17] 个对象的数组=] 对象,array_ptr 指向该数组的第一个元素。它只创建指针本身。

与:

printf("array_ptr: %p \narray_ptr+1: %p\n", array_ptr, array_ptr+1);

您正在尝试打印指针 array_ptr 的对象地址及其偏移 1 点,但这是不可能的,因为 array_ptr 未初始化为指向此类对象。因此,您会得到任何类型的 Undefined Behavior/ 不可预测的结果。

您需要用 f.e 初始化 array_ptrarray 的第一个 int 对象的地址:

int (*array_ptr)[100] = array;

同样适用于指针 ptr 与:

printf("ptr: %p\n", ptr);

ptr 需要有它指向的对象的地址才能显示该对象的地址。

But the dynamically allocated memory chunk pointed by buff is also supposed to be in heap and its value changes, why is that?

这是完全不同的事情。使用 mallocdo 在堆上分配内存(当然如果它成功的话)并且你 do 得到一个指向该内存的指针回来,int (*array_ptr)[100];.

不是这种情况

array_ptr 是未初始化的指针,并获得未定义的值(在您的情况下为 0)。

array_ptr+1 比 array_ptr

多 sizeof(int)*100 = 400 = 0x190

ptr 也是一个 uninit 指针,在你的例子中它指向垃圾。

您需要在定义指针后对其进行初始化以获得任何有效结果

对于你的问题,array在栈上,buff在堆上,ptr/array_ptr未初始化会给你垃圾或分段错误如果您尝试访问他们的数据