首页 > 解决方案 > 为什么指针显示的是值而不是地址?

问题描述

我有这个代码:

int *array_ptr{nullptr}; 
array_ptr = new int[10]; // allocate array on the heap
    
for(int i=0; i<10; i++){
    array_ptr[i] = i;
    std::cout<<array_ptr[i]<<std::endl;
}

delete [] array_ptr; // deletes allocated space

据我了解,int *array_ptr显示实际值,而int array_ptr没有取消引用运算符则显示内存中的地址。

那么,为什么array_ptr[i]显示0 1 2 3 4 ... 10,而不是显示地址1000、1004、1008...等。(地址编造)。

标签: c++arraysc++11pointersc++17

解决方案


指针的意思是“指示地址中有哪个值?”

如果要查看变量的寻址,则必须使用 & 运算符。

在 for 循环中试试这个

std::cout << &array_ptr[i] << std::endl;

推荐阅读