0

Why is it that I can do....

int numbers[100];
int * intPtr = numbers;

NOT using the address of operator but...

typedef struct {
    int x;
    int y;
} Vec2D;

Vec2D vec;
Vec2D * vecPtr = &vec;

That is, why is the address of operator required on the struct? Why isn't vec an address?

Cody Smith
  • 2,732
  • 3
  • 31
  • 43

2 Answers2

2

Your analogy is broken: The fair comparison would be between Vec2D * and int (*)[100], i.e. pointers to the object. However, in your first piece of code, you are obtaining a pointer to a subobject using an unrelated language mechanism (array-to-pointer decay).

The following works as expected:

typedef int T[100];
T numbers;
T * p = &numbers;   // or: int (*p)[100] = &numbers;

typedef Vec2D T;
T vec;
T * p = &vec;       // or: Vec2D * p = &vec;

Pointers to subobjects can also be taken:

int * p_elem = &numbers[0];
int * v_emen = &vec.x;

The only special magic rule is that the array expression numbers can decay to the address of its first element, so &numbers[0] is the same as (the result of) numbers:

int * p_elem = numbers;  // same as &numbers[0]
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
1

Arrays of size N are basically a pointer to a contiguous chunk of memory containing N objects. The [i] operator specifies the offset from the pointer where the ith object is. So basically numbers by itself is just a pointer.
For instance,

int main(){
int numbers[100];
numbers[0] = 1;
printf ("%d\n", numbers);
}

will throw an error because numbers it a pointer, not an integer.

Tim Sanch.
  • 81
  • 3