C Programming Pointers and Arrays

Last modified by Microchip on 2023/11/09 09:06

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.

Pointers and Arrays

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:

1 int x[5] = {1,2,3,4,5};
2 int *p;

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

1 p = x;      //Works only for arrays!
2 p = &x;     //Works for arrays or variables
3 p = &x[0];  //This one is the most obvious

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.