Pointers and Arrays

Let's take a quick look at arrays again. Recall that array elements occupy consecutive memory locations. Because of this, if you know the address of the first element of an array, you can easily move through the array by incrementing the address or adding an offset to that address. While we could do this with the ordinary array syntax by incrementing or adding a value to the array offset, we could also do this with pointers.


Initializing a Pointer to an Array

Creating a pointer to an array is just like creating a pointer to any other variable. However, because of the unique nature of arrays, there are additional ways you can initialize pointers to arrays.

If we declare the following array and pointer variable:

We can initialize the pointer to point to the array using any one of these three methods:

The first method is to simply assign the array variable to the pointer variable. By definition, an array variable without the square brackets and index represents the address of the array, which is also the address of the first element. So, we can simply say p = x; without the & (address of) operator.

The second method is where we use the same syntax as when we assign an ordinary variable's address to a pointer. This syntax is much easier to remember since it works for both variables or arrays.

The final syntax is virtually never used, even though it is perfectly correct to use and is the only syntax that makes it perfectly obvious what is going on. But it requires more typing, and C programmers hate to type more than necessary…

© 2017 Microchip Technology, Inc.
Notice: ARM and Cortex are the registered trademarks of ARM Limited in the EU and other countries.
Information contained on this site regarding device applications and the like is provided only for your convenience and may be superseded by updates. It is your responsibility to ensure that your application meets with your specifications. MICROCHIP MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED, WRITTEN OR ORAL, STATUTORY OR OTHERWISE, RELATED TO THE INFORMATION, INCLUDING BUT NOT LIMITED TO ITS CONDITION, QUALITY, PERFORMANCE, MERCHANTABILITY OR FITNESS FOR PURPOSE. Microchip disclaims all liability arising from this information and its use. Use of Microchip devices in life support and/or safety applications is entirely at the buyer's risk, and the buyer agrees to defend, indemnify and hold harmless Microchip from any and all damages, claims, suits, or expenses resulting from such use. No licenses are conveyed, implicitly or otherwise, under any Microchip intellectual property rights.