C Tutorial, Part V
Pointer Arithmetic
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:
For any array, arrayName, integer, i,
and pointer variable, ptr:
- arrayName[i] == *(arrayName + i)
AND
- ptr + i == ptr + (i * sizeof( *ptr ))
/* recall that *ptr is the object that ptr points to */
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
Pointer Arithmetic and Casting