本文介绍了二维数组如何存储在内存中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int a[101][101];
    a[2][0]=10;
    cout<<a+2<<endl;
    cout<<*(a+2)<<endl;
    cout<<*(*(a+2));
    return 0;
}

为什么a + 2和*(a + 2)的值相同?预先感谢!

Why are the values of a+2 and *(a+2) same? Thanks in advance!

推荐答案

a是2D数组,表示数组的数组.但是在适当的上下文中使用时,它会衰减指向数组的指针.所以:

a is a 2D array, that means an array of arrays. But it decays to a pointer to an array when used in appropriate context. So:

  • a+2中,a衰减为指向大小为101的int数组的指针.当传递给ostream时,您将获得此数组的第一个元素的地址,即&(a[2][0])
  • 根据定义,*(a+2)中的
  • a[2]:它是大小为101的数组,起始于a[2][0].它衰减为一个指向int的指针,当您将其传递给ostream时,您将获得其第一个元素的地址,该地址仍为&(a[2][0])
  • **(a+2)根据定义是 a[2][0].当您将其传递给ostream时,将获得其int值,此处为10.
  • in a+2, a decays to a pointer to int arrays of size 101. When you pass is to an ostream, you get the address of the first element of this array, that is &(a[2][0])
  • in *(a+2) is by definition a[2]: it is an array of size 101 that starts at a[2][0]. It decays to a pointer to int, and when you pass it to an ostream you get the address of its first element, that is still &(a[2][0])
  • **(a+2) is by definition a[2][0]. When you pass it to an ostream you get its int value, here 10.

但是要注意:a + 2a[2]都是指向相同地址的指针(static_cast<void *>(a+2)static_cast<void *>(a[2])相同),但是它们指向的是不同类型的指针:第一个指向大小为101的int数组,后者转换为int.

But beware: a + 2 and a[2] are both pointers to the same address (static_cast<void *>(a+2) is the same as static_cast<void *>(a[2])), but they are pointers to different types: first points to int array of size 101, latter to int.

这篇关于二维数组如何存储在内存中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 09:15
查看更多