# 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;    // 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;     // 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;  // 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
p = p + 1;   // Adds 4 to p (4 == 1 * sizeof(int)). Ie, &b
```

## 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;  // 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
*p = 14;     // Same as b = 14
p = p + 1;   // Adds 4 to p (4 == 1 * sizeof(int)). Ie, &b
*p = 22;     // Same as b = 22;
```

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

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