c++ - 二维数组指针 - 访问元素和地址

标签 c++ pointers

我正在学习二维数组指针,这是我的代码。我不知道为什么这一行:

cout<<"Address of 1st part = "<<*ptr`  

当这条线显示地址时没有显示地址:

cout<<"Address of 1st part = "<<*(A)`  

这两条线的意思相同,任何人都可以帮助我。

#include <iostream>
using namespace std;


int main()
{
    int A[2][3]={{1,2,4},{5,8,3}};

    int *ptr;
    ptr=&A[0][0];

    cout<<"Address 1st part = "<<A<<endl;
    cout<<"Address 2nd part = "<<A+1<<endl;

    cout<<"Address 1st part = "<<ptr<<endl;
    cout<<"Address 2nd part = "<<ptr+1<<endl;

    cout<<"Address of 1st part = "<<*(A)<<endl;
    cout<<"Address of 1st part = "<<*ptr<<endl;

    cout<<"Address"<<*(A+1)+1<<endl;

    cout<<*(A+1)+2<<endl;

    return 0;
}

输出

Address 1st part = 0x7fffb6c5f660 
Address 2nd part = 0x7fffb6c5f66c 
Address 1st part = 0x7fffb6c5f660 
Address 2nd part = 0x7fffb6c5f664 
Address of 1st part = 0x7fffb6c5f660 
Address of 1st part = 1 
Address0x7fffb6c5f670 
0x7fffb6c5f674

最佳答案

这两行实际上并不意味着相同。多维数组不等同于指向其原始类型的指针。

Aint [2][3] 类型,等同于 int *[3]*A 的类型是int[3],不是int。连续指向元素 sizeof *A 之间的步长等于 sizeof(int)*3

ptrint * 类型。 *ptr 的类型是int。这里的步骤 sizeof *ptr 等于 sizeof(int)

关于c++ - 二维数组指针 - 访问元素和地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21368333/

相关文章:

c++ - 如何将 Windows SOCKADDR_BTH 的 C++ 转换复制到 Rust 中的 SOCKADDR?

c - C中带指针的字符串数组

c - 使用 malloc() 作为唯一指针

Objective-C:一个在不同时间指向不同类的指针

c++ - Qt 启动画面不显示

c++ - QMenu* << QAction* -- 帮我写一个全局 QMenu 插入操作符

c++ - 动态数组分配末尾的()是什么意思?

c++ - 使用由结构指向的指针中的变量,该结构(该结构的)指针被发送到需要使用它的函数

java - 多线程 JNI 调用

c++ - 如何就地构建可选聚合?