Ken H

Ken H

  • NA
  • 646
  • 361.7k

pointer to the array in c++?

Mar 22 2015 2:32 AM
Hello friend,
 
  I have a confused, see the following code:


#include <iostream>
using namespace  std;

int main(void){

  int a[4]={1,2,3,4};  // 1D int array.
  int a2[3][4]={{1,2,3,4},{5,7,8,9},{10,11,12}}; // 2D int array.
  int (*p)[4]=NULL;

  // Their address is:
  cout<<"a="<<a<<endl;
  cout<<"&a="<<&a<<endl;
  for (int i=0;i<4;i++)
  {
    cout<<"&a["<<i<<"]="<<&a[i]<<"  ";
  }
  cout<<"\n\n";

  cout<<"a2="<<a2<<endl;
  cout<<"&a2="<<&a2<<endl;
 
  for (int i=0;i<3;i++)
  {
    for (int j=0;j<4;j++)
    {
      cout<<"&a2["<<i<<"]["<<j<<"]="<<&a2[i][j]<<"  ";
    }
    cout<<endl;
  }
  cout<<"\n\n";
 
  /*
  The output is:

  a=002EFDAC
  &a=002EFDAC
  &a[0]=002EFDAC  &a[1]=002EFDB0  &a[2]=002EFDB4  &a[3]=002EFDB8

  a2=002EFD74
  &a2=002EFD74
  &a2[0][0]=002EFD74  &a2[0][1]=002EFD78  &a2[0][2]=002EFD7C  &a2[0][3]=002EFD80

  &a2[1][0]=002EFD84  &a2[1][1]=002EFD88  &a2[1][2]=002EFD8C  &a2[1][3]=002EFD90

  &a2[2][0]=002EFD94  &a2[2][1]=002EFD98  &a2[2][2]=002EFD9C  &a2[2][3]=002EFDA0
 
  We found the following equivalence relation(memory address):

   1)a=&a=&a[0]=002EFDAC
   2)a2=&a2=&a2[0][0]=002EFD74

  */

  // Okay, time for a quiz:
 
  p=a;  // Error C2440: "=": not available from "int [4]" convert "int (*) [4]".
  p=&a; // This line is correct.we know that a and &a are equal(memory address),why p=a is error?

  p=a2; // This line is correct.
 
  system("pause");
  return 1;
}


Thank.

Regards

Ken.

Answers (7)