C++ Notes: Arrays as Pointers

Using an array name as a pointer

An array name is really a pointer to the first element of the array. For example, the following is legal.
   int b[100];    // b is an array of 100 ints.
   int* p;        // p is a pointer to an int.
   p = b;         // Assigns the address of first element of b to p.
   p = &b[0];     // Exactly the same assignment as above.

Array name is a const pointer

When you declare an array, the name is a pointer. You cannot alter the value of this pointer. In the previous example, you could never make this assignment.
   b = p;   // ILLEGAL because b is a constant, altho the correct type.

Pointer arithmetic

You can do arithmetic on pointers, if the result can be a meaningful pointer or integer.

Pointer addition and element size

When you add an integer to a pointer, the integer is multiplied by the element size of the type that the pointer points to.
// Assume sizeof(int) is 4.
int b[100];  // b is an array of 100 ints.
int* p;      // p is a a pointer to an int.
p = b;       // Assigns address of first element of b. Ie, &b[0]
p = p + 1;   // Adds 4 to p (4 == 1 * sizeof(int)). Ie, &b[1]

Equivalence of subscription and dereference

Because of the way C/C++ uses pointers and arrays, you can reference an array element either by subscription or * (the unary dereference operator).
int b[100];  // b is an array of 100 ints.
int* p;      // p is a a pointer to an int.
p = b;       // Assigns address of first element of b. Ie, &b[0]
*p = 14;     // Same as b[0] = 14
p = p + 1;   // Adds 4 to p (4 == 1 * sizeof(int)). Ie, &b[1]
*p = 22;     // Same as b[1] = 22;
Understand the following remarkable equivalence (a is an array and i is an integer).
    a[i] == *(a + i) == *(i + a) == i[a]
Altho these are equivalent, never, ever, write i[a] instead of a[i].

Example - Two ways to add numbers in an array

The first uses subscripts, the second pointers. They are completely equivalent.
int a[100];
. . .
int sum = 0;
for (int i=0; i<100; i++) {
   sum += a[i];
}
   
int a[100];
. . .
int sum = 0;
for (int* p=a; p<a+100; p++) {
   sum += *p;
}