C ++:二维数组中的指针令人困惑 [英] C++: Pointers in 2D-arrays are confusing

查看:49
本文介绍了C ++:二维数组中的指针令人困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以向我解释这里发生了什么吗?考虑代码

Can someone explain to me what is going on here? Consider the code

#include <iostream>

int main()
{
    int A[2][2] = {{0}};

    std::cout << A << std::endl;  // First stdout line
    std::cout << *A << std::endl;  // Second stdout line
    std::cout << *(*A) << std::endl;  // Third stdout line
}

(在此处尝试代码!)

在我看来,A应该是2个指向数组的指针的数组,每个指针都应包含2个指向int s的指针.但是,在运行代码时,会将以下内容写入stdout:

It seems to me that A should be an array of 2 pointers to arrays, each of which should contain 2 pointers to ints. However, when running the code, the following is written to stdout:

0x7a665507cf80
0x7a665507cf80
0

在我看来,这似乎A中的第一个元素的内存地址(打印在第一条标准输出行上)与*A中的第一个元素的内存地址相同.考虑到A*A显然是两个不同的数组(因为对A*A的解引用给出不同的结果),这怎么可能?

To me, this makes it seem like the memory address of the first element in A (printed on the first stdout line) is the same as the memory address of the first element in *A. How is this possible, considering that A and *A are clearly two different arrays (since dereferencing A and *A gives different results)?

对输出的另一种解释是,存储器地址0x7a665507cf80包含值0x7a665507cf80(即位于该位置的指针,在本例中为A指向自身)或0,具体取决于是从A还是*A访问的,这对我来说真的没有任何意义.

An alternative interpretation of the output is that the memory address 0x7a665507cf80 either contains the value 0x7a665507cf80 (i.e. a pointer located on that position—in this case A—points to itself) or 0, depending on if it is accessed from A or *A, which also doesn't really make sense to me.

推荐答案

int A[2][2] = {{0}};这是一个静态2D数组,它不是指向指针的指针,它只是具有特殊访问权限的1D数组.

int A[2][2] = {{0}}; This is a static 2D array, it's not a pointer to pointer, it's just a 1D array with special access.

它不是指向指针的指针,而是1D数组上的2D数组,这一事实意味着A[0]*A访问该数组并返回作为第一行的1D数组.然后,第二次取消引用就获得了实际值.如果您有int A[x][y][z][t]...,这将概括为nD.

The fact that it's not a point to pointer, but a 2D array on a 1D array means that A[0] or *A accesses the array and returns the 1D array that is the first row. Then the second dereferentiation gets the actual value. This generalizes to nD if you have int A[x][y][z][t]....

所以前两个是相同"地址,但它们不是同一类型.

So the first two are the "same" address, but they are not the same type.

这篇关于C ++:二维数组中的指针令人困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆