Pointer Comparison with Arrays
Pointers and Arrays
As we have already learned, arrays are collections of objects of the same type
E.g., the statement int myInts[100]; reserves memory space for 100 integer objects and refers (or names) this space myInts.
To get at any individual element (or object), we indicate which one we want by providing an index, e.g., myInts[7] allows us to access the *eighth* element of the array (remember we start counting at zero).
When we refer to myInts in our program without any index, the compiler sees the name as a reference (or pointer) to the entire array.
For example, in the following program fragment, the pointer variable ptr is set to point to the beginning of the array with the assignment ptr = myInts; In this case, since the array is an array of integers, the variable ptr must be a pointer to integers or the compiler will complain of mis-matched types.
When pointers refer to arrays, they can be indexed just like the original array (see the last statement in the program fragment below).
int myInts[100]; // declare an array of 100 integers
int *ptr; // declare a pointer variable (a pointer to int)
ptr = myInts; // causes ptr to point to the beginning of the array, just as myInts does
ptr[3] = 10; // sets the fourth element of the array myInts to 10.
So then, an array name is a pointer. The only difference array names and general pointers is that array names are constant. That is, they cannot be reassigned to point to other things (see example below):
// suppose after the program fragment above, you had the following code
// the first assignment is acceptable, because ptr can be assigned to point to any
// valid integer (i.e,. either those in myInts or those in yourInts); however the
// second assignment is unacceptable, because the myInts pointer cannot be
// reassigned (since it is an array name)
int yourInts[100];
ptr = yourInts;
myInts = yourInts;
Understanding the above, it should now make sense that all arrays are automatically passed to functions as reference parameters. Because when we use the array name as a parameter, we are referring to the actual array (because the array name is a pointer) rather than a copy of the array.