C Programming 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:
2 int *p;
We can initialize the pointer to point to the array using any one of these three methods:
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.