2

According to my class notes, you can allocate an array in C++ like

int *A = new int[5]

where A is a pointer to the array.

But then you can access the array as A[3]. Why can you do that? Isn't A a pointer and not the actual array?

1
  • as for the type: A is of type "pointer to int". But it points to the first element of a dynamically allocated int array, yes. Commented Jan 6, 2012 at 18:14

4 Answers 4

5

The indexing operator[] actually defined to work on pointers, not on arrays. A[3] is actually a synonym for *(A+3). It works on arrays as a consequence of the fact that arrays can be implicitly converted to pointers to their first element.

Sign up to request clarification or add additional context in comments.

2 Comments

I've never heard it explained that way - neat :) +1.
@w00te: that's not really an explanation. It is the definition with all its consequences: 3[A] for example.
3

A[3] is an alias for *(A+3) which dereferences the pointer.

Comments

1

You are right! Basically, this is syntactic sugar, meaning that the language designers put something in place to make your life a bit easier, but behind the scenes it is doing something quite different. (This point is arguable)

Effectively, what this is doing is taking the pointer location at A, moving the pointer 5 int-sizes up, then giving you the value by dereferencing.

Comments

1

This is the starting point of pointer arithmetic: you can add or subtract values with pointers, as long you don't move off the array (well, you can move up to right after the array). Basically, the following hold (for A being a pointer to an array with at leat i + 1 elements:

A[i]
*(A + i)  // this what A[i] means
*(i + A)  // addition is commutative
i[A]       // this sould work, too - and it does!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.