Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
163 views
in Technique[技术] by (71.8m points)

c++ - Why is the same value output for A[0], &A, and *A?

I am doing a little experiment.

#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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The first thing to understand is what you are printing:

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

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].

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...