-1
#include <cstdio>

typedef struct {
  int a;
  int b;
  int c;
} Foo;

int main() {
  Foo foo[42];
  printf("foo = %p\n", foo);
  printf("&foo = %p\n", &foo);
  return 0;
}

When I compile this program with g++ and run it, it produces the following output.

foo = 0xbf8caea8
&foo = 0xbf8caea8

This is not what I expected. When I derefence foo, I would expect to get the value of foo[0].a and when I dereference &foo, I would expect to get a pointer on foo[0].a.

How can these two pointers be equal?

MBober
  • 1,095
  • 9
  • 25

1 Answers1

1

Think of them as addresses rather than pointers, because &foo there for example is not a pointer, rather just the address of the foo variable.

What does the foo variable stand for?

It stands for the array of Foos you've declared. This array starts from a point in memory, exactly where the first element of the array starts, logically.

Think of a chain in real life. The whole chain starts from the exact same location as the flrst bit of chain starts. Their sizes are different, but both originate from the same location in space.

The case is just like that for arrays. &foo is where the whole chain starts, &foo[0] - which is what foo is - starts from that same location.

Utkan Gezer
  • 3,009
  • 2
  • 16
  • 29
  • 1
    My problem was that I thought that `foo` always decays to a pointer to `foo[0]`. I wasn't aware of the fact that this is true **unless `foo` is an operand of unary operator `&`** (or `sizeof`). – MBober Aug 14 '14 at 10:06