Are Pointers and Arrays Interchangeable?

1.Are Pointers and Arrays Interchangeable?

As the preceding few pages have shown, pointers and arrays are strongly related. In fact, pointers and arrays are interchangeable in many cases. For example, a pointer that points to the beginning of an array can access that array by using either pointer arithmetic or array-style indexing. However, pointers and arrays are not completely interchangeable. For example, consider this fragment:
int num[10];
int i;
for(i=0; i<10; i++) {
*num = i; // this is OK
num++; // ERROR -- cannot modify num

Here, num is an array of integers. As the comments describe, while it is perfectly acceptable to apply the * operator to num (which is a pointer operation), it is illegal to modify num’s value. The reason for this is that num is a constant that points to the beginning of an array. Thus, you cannot increment it. More generally, while an array name without an index does generate a pointer to the beginning of an array, it cannot be changed. Although an array name generates a pointer constant, it can still take part in pointer-style expressions, as long as it is not modified. For example, the following is a valid statement that assigns num[3] the value 100: 
*(num+3) = 100; // This is OK because num is not changed
Share on Google Plus