# 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, which cannot be altered. In the previous example, you could never make this assignment.

       p = b;   // Legal -- p is not a constant.
       b = p;   // ILLEGAL because b is a constant, altho the correct type.

## Pointer arithmetic

"Meaningful" arithmetic operations are allowed on pointers.

- Add or subtract integers to/from a pointer. The result is a pointer.
- Subtract two pointers to the same type. The result is an int.
- Multiplying, adding two pointers, etc. don't make sense.

## 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;

## Example - Two ways to add numbers in an array

The first uses subscripts, the second pointers. They are 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;
    }