使用指针显示多维数组中的元素

using pointers to display elements from a multidimensional array

您好,我刚刚开始了解指针和数组,我或多或少知道如何在一维数组中操作指针以显示元素。但是在多维数组中呢? 我一直在练习这段代码:

#include<iostream>
using namespace std;
int main()
{

    int a[2][3]= { {1,2,3},{4,5,6}};
    int (*ptr)[3] = &a[0]; // or (*ptr)[3] = a;

    cout <<"Adress 0,0: "<< a << endl;
    cout <<"Adress 0,0: "<< ptr << endl;         
    cout <<"Value 0,0: "<< *a[0] << endl;
    cout <<"Value 0,0: "<< *(ptr)[0]<< endl;
    cout <<"Adress 0,1: "<< &a[0][1] << endl;
    cout <<"Adress 0,1: "<< (ptr)[1] << endl;       

    return 0;
}

我已经成功地使用数组名和指针显示了 a[0][0] 的地址和值,但是如何显示 a[0][1] 的地址和值以及后续元素通过使用指针?

(ptr)[1](与ptr[1]相同)不指向a[0][1],它指向a[1][0],因为您将ptr定义为指向int[3],而不是 int。因此,使用 ptr[1]ptr 递增 1 会跳过三个 int,直到 a[1][0].

ptr 增加一个 int 而不是三个 int 的大小:

ptr[0] + 1

以上会指向a[0][1]。并访问它:

*(ptr[0] + 1)
    #include<iostream>
    using namespace std;

    int main()

{

    int a[2][3]= { {1,2,3},{4,5,6}  };
    int (*ptr)[3] = &a[0]; // or (*ptr)[3] = a;

    cout <<"Adress 0,0: "<< a << endl;
    cout <<"Adress 0,0: "<< ptr << endl;         
    cout <<"Value 0,0: "<< *a[0] << endl;
    cout <<"Value 0,0: "<< *((ptr)[0]+0)<< endl;
    cout <<"Adress 0,1: "<< &a[0][1] << endl;
    cout <<"Adress 0,1: "<< (ptr)[0]+1 << endl;       
    cout <<"value 0,1: "<<  a[0][1] << endl;
    cout <<"value 0,1: "<< *((ptr)[0]+1) << endl;

    cout <<"Adress 1,0: "<< &a[1][0] << endl;
    cout <<"Adress 1,0: "<< (ptr)[1] << endl;       
    cout <<"value 1,0: "<<  a[1][0] << endl;
    cout <<"value 1,0: "<< *((ptr)[1]+0) << endl;       

    return 0;
}

希望这能消除您的疑虑。