Consider an array of double
:
double myArray[5] = { 3, 6, 9, 12, 15 };
Value Type myArray[0] double &myArray[0] double *
An array name by itself evaluates to
the address of the first element.
(Just like a string constant evaluates to the
address of the first element.)
Example:double * dPtr = &myArray[0]
ORdouble * dPtr = myArray
.
We can step through an array using pointers.
char myCharArray[5] = { 'a', 'b', 'c', 'd', 'e' }; char * ptr; for ( ptr = myCharArray; ptr < myCharArray + 5; ptr++ ) { printf("%c", *ptr); }
When we increment a pointer, it is actually incremented by the size of the thing it points to. (Same thing if we add an integer to a pointer; it gets incremented by the specified number of things of that size.) So, incrementing a pointer by 1 always causes it to point to the next item of that type, regardless of what type it is.
double * dptr; for ( dptr = myArray; dptr < myArray + 5; dptr++ ) { printf("%Lf", *dptr); }
Arrays and pointers can be used interchangeably. In fact,
Arrays are just syntactic sugar (except in variable declarations, where they specify the amount of memory set aside).
Array Expression Equivalent Pointer Expression myArray[0] *myArray &myArray[0] myArray &myArray[1] myArray + 1 &myArray[3] myArray + 3 myArray[3] *(myArray + 3)