# C Tutorial, Part V

## Pointer Arithmetic

Look at the following code segment found in arrayPtr.c

```char *wordArray[MAX_WORDS];  /* compile-time array of char* */
char **wordArray2;  /* pointer to char* */
char matrix[MAX_WORDS][30];

wordArray2 = (char**)malloc(MAX_WORDS * sizeof(char*));
/* wordArray2 is now a MAX_WORDS-size array of char*'s */
```

### The semantics of using the names wordArray and wordArray2 are as follows:

• wordArray - a synonym for the value of the address of the first element of wordArray
• wordArray2 - a variable that stores the address of the first element of wordArray2
• wordArray + i - the value of the address of the i'th element of wordArray
• wordArray2 + i - the value of the address of the i'th element of wordArray2
• wordArray2[i] - dereferences wordArray2 and produces the value stored in the i'th position
• thus, wordArray2[i] is equivalent to *(wordArray2 + i)

### Which leads us to the "Fundamental Theorems" of Pointer Arithmetic:

#### An interesting corollary (which we'll see below): (char *)ptr + 4   ==   (int *)ptr + 1

Lets spend some time passing various arguments to the different array functions and, in particular, see the warning generated by the call of the `printMatrix` routine. The correct prototype is `void printMatrix(char arr[][30]);` or `printMatrix(char (*arr)[30]);`.

### Applications of Pointer Arithmetic to strings

Here are some small programs that illustrate common uses of pointer arithmetic:

• In ptrArith_1.c we simply dereference the array's name to access the first char of the array.

• In ptrArith_2.c we use pointer arithmetic to copy from one string to another.

• In ptrArith_3.c we use a slightly more compact syntax to copy from one string to another.

• In ptrArith_4.c we condense the copy to its minimal form. Get used to reading this kind of code!

• In ptrArith_5.c we just move the copy line into a function.

#### Pointer Arithmetic and Casting

In ptrCast.c we mix casting with pointer arithmetic to do something funky...