Pointers to Arrays

Arrays are contiguous blocks of memory holding multiple objects of the same type. These can be quite large and passing them into functions in the conventional, by value sense, can be quite inefficient both in terms of memory and processor cycles.

Fortunately, pointers come to our rescue here by allowing us to pass a pointer to an array into a function rather than passing the array itself. That way we only store the array in memory in one place and we just refer to or reference that one location whenever we need access to the data in the array.

Arrays themselves are quite lie pointers in fact. An array variable, for example arr in a statement like int arr[3] = {1,2,3} points to the address of the first object in the array. So int *ip = &arr[0] is the same as doing int *ip = arr

Pointers and arrays are related but not quite the same. For example, suppose we set up a couple of arrays: int arr1[3] = {11,12,13}; int arr2[3] = {14,15,16}; You can then do, as we just saw, int *ip = arr1; However, if you were to assume arrays and pointers work identically then you might think you could do arr = ip; or even arr1 = arr2; or arr = &arr2[0]; but all of those will throw compiler errors.

Leave a Reply

Your email address will not be published. Required fields are marked *