为什么A [0],& A和* A输出相同的值? [英] Why is the same value output for A[0], &A, and *A?

查看:122
本文介绍了为什么A [0],& A和* A输出相同的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在做一些实验。

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

  int A[5][5];
  cout<<A[0]<<"  "<<&A<<"   "<<*A;
  return 0;
}

对所有情况打印相同的值。

It prints the same value for all cases. Can somebody explain why this is the case?

推荐答案

首先要了解的是您要打印的内容:

The first thing to understand is what you are printing:

 cout<<A[0]<<"  "<<&A<<"   "<<*A;

表达式 A [0] 表达式类型 int [5] 引用 A 是指向数组 A的类型 int(*)[5] [5] 的右值表达式。最后 * A 等价于 A [0] ,这是类型 int [5]

The expression A[0] an lvalue expression with type int[5] referring to the first internal array inside A, &A is an rvalue-expression of type int (*)[5][5] that points to the array A. Finally *A is equivalent to A[0], that is an lvalue expression of type int[5].

在语言中没有定义操作符(也不能提供) $ c> int [5] int(*)[5] [5] ,因此编译器尝试查找最佳匹配,并且发现有一个操作符打印 void * int [5] 可以衰减为 int * ,表示 A [0] 0] ,它本身可以转换为 void * int(*)[5] [5] 是一个指针,因此可转换为 void *

There are no operators defined in the language (nor can you provide them) that will dump either a int[5] or a int (*)[5][5], so the compiler tries to find the best match it can and finds that there is an operator that prints a void*. int[5] can decay into a int* that refers to A[0][0], and that is itself convertible to a void*. int (*)[5][5] is a pointer and thus convertible to void*, so that overload is valid for both cases.

语言定义了一个数组在内存中的布局,特别是它需要数组和数组的第一个元素布局在因此如果要打印& A & A [0] 的地址,它将打印相同的值,并且因为& A [0] 也在其第一个元素的相同存储器位置,&

The language defines the layout of an array in memory, and in particular it requires that the array and the first element of the array are laid out in the same memory address, so if you were to print the addresses of &A and &A[0] it would print the same value, and because &A[0] is also in the same memory location of the first of its elements, &A[0][0] also refers to the same address.

回到上面你打印的代码是:

Going back to the code above what you are printing is:

cout<<         static_cast<void*>(&A[0][0]) 
    << "  " << static_cast<void*>(&A)
    << "  " << static_cast<void*>(&A[0][0]);

在上述推理之后必须具有相同的精确值,即使类型不同第二种情况。

which following the reasoning above must have the same exact value, even if the type is not the same in the second case.

这篇关于为什么A [0],&amp; A和* A输出相同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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