0

When I run following program:

int a[3][4];
int k = 0;
for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 4; j++)
    a[i][j] = k++;

}

cout<<"a:  "<<a<<endl;
cout<<"&a: "<<&a<<endl;

output procudced is something like this:

a: 002FFB4C &a: 002FFB4C

Why are values same? should it not be different?

sachin
  • 1,376
  • 2
  • 15
  • 37

2 Answers2

3

Technically, they can, but they need not - the C standard says nothing about the exact numerical value of pointers. By the way, I find it quite logical that they're the same - arrays are not pointers, so a can decay into a pointer to its first element, and &a is a pointer to a, which may quite obviously be the same as a pointer to its first element:

+------------------+------------------+- - - -
| 1st element of a | 2nd element of a |
+------------------+------------------+- - - -
^ pointer to first element
^ pointer to a (as well)
  • *"the C standard says nothing about the exact numerical value of pointers"*. I think it mandates (or it logically follows from the layout of array of arrays)? – Nawaz Jul 23 '13 at 16:03
  • @Nawaz As far as I remember, it only requires that the pointers are interchangeable **if "suitably converted"** (i. e. after typecasting). –  Jul 23 '13 at 16:27
0

In your code, a is the address of the first element of array of array — which is a[0]. Its address concides with the address of a itself. Not only that it is same as a[0], &a[0] and &a[0][0].

Here is an interesting experiment:

#include <cstdio>

#define print(a) std::printf("%10s: %p\n", #a, a);

int main() 
{
    int a[3][4];
    print(&a);
    print(a);
    print(a[0]);
    print(&a[0]);
    print(&a[0][0]);
}

Output:

        &a: 0xbfafca80
         a: 0xbfafca80
      a[0]: 0xbfafca80
     &a[0]: 0xbfafca80
  &a[0][0]: 0xbfafca80

Online Demo. :-)

Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • I think you should mention that the standard doesn't mandate this, though. –  Jul 23 '13 at 16:02
  • @H: I think it mandates (or it logically follows from the layout of array of arrays)? – Nawaz Jul 23 '13 at 16:04