C++数组指针与指针数组-做一个区分

//
// Created by 徐昌真 on 2024/9/29.
//
#include <iostream>
using namespace std;

string getHex(int x){
    char buff[10];
    sprintf(buff, "%X", (x & 0xFFFF));
    return (string)buff;
}

int main() {

    int a[3][4] = {
            {1,2,3,4},
            {5,6,7,8},
            {9,10,11,12}
    };

    for(int i = 0; i < 3; ++i){
        for(int j = 0; j < 4; ++j){
            if(j){
                cout << ',' ;
            }
            int *p = &a[i][j];
            cout << getHex((uintptr_t)p);
        }
        cout << endl;
    }

    //指针数组
    int* p[3] = {&a[0][0],&a[1][0],&a[2][0]};  //指针指向指针的地址(指针的指针)
    //数组指针
    int(*q)[4];
    q = &a[0];  //还是取了地址

    cout << "指针 + i" << endl;
    cout << "指针数组" << endl;  //得到的是地址的地址
    for(int i = 0; i < 3; ++i) {
        string s = getHex((uintptr_t) (p + i));
        cout << "第" << i << "个p元素的地址是" << s << endl;
    }
    cout << "数组指针" << endl;  //得到每行的地址
    for(int i = 0; i < 3; ++i){
        string s = getHex((uintptr_t)(q + i));
        cout << "第" << i << "个[4]数组的地址是" << s << endl;
    }

    cout << *("指针 + i") << endl;
    cout << "指针数组" << endl;  //对指针解引用 得到数组里的元素 &a[][]
    for(int i = 0; i < 3; ++i) {
        string s = getHex((uintptr_t) *(p + i));
        cout << "a数组第" << i << "行第0个元素的地址是" << s << endl;
    }

    cout << "数组指针" << endl;  //这是每行第0个元素的地址   每行的地址等于每行第0个元素的地址
    for(int i = 0; i < 3; ++i){
        string s = getHex((uintptr_t) *(q + i));  //对每行的地址解引用后 得到每行第0个元素的地址
        cout << "a数组第" << i << "行第0个元素的地址是" << s << endl;
    }

    cout << "*(指针 + i) + j" << endl;
    cout << "指针数组" << endl;  //对指针解引用 得到数组里的元素 &a[][]
    for(int i = 0; i < 3; ++i) {
        string s = getHex((uintptr_t) (*(p + i) + 1 ));
        cout << "a数组第" << i << "行第0个元素的地址是" << s << endl;
    }

    cout << "数组指针" << endl;  //这是每行第0个元素的地址   每行的地址等于每行第0个元素的地址
    for(int i = 0; i < 3; ++i){
        string s = getHex((uintptr_t) (*(q + i) + 1 ));  //对每行的地址解引用后 得到每行第0个元素的地址
        cout << "a数组第" << i << "行第0个元素的地址是" << s << endl;
    }






    return 0;
}

输出结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值