When you declare an array, a contiguous memory is allocated.
int a[5] = {1}
int *iPtr; int a[5]; iPtr = &a[1];The pointer variable is pointing to the 2nd element of the array.
iPtr2 = iPtr1 + 1;
``Add 1'' to a pointer variable?? This seems weird, but it has a
special meaning. This gives an address of the next element in the
array to iPtr2.
*iPtr2 = 4;
The value of the 3rd element (a[2]) become 4.
*(iPtr2 - 2) = 0;
int b[20], *ptr; /* initialize array b here */ for (i = 0, ptr = &b[0]; i < 5; i++, ptr +=2) { printf ("%d ", *ptr); }
int array1[10], array2[10]; int *iPtr1, *iPtr2 = &array2[0], *endPtr = &array1[10]; for (iPtr1 = &array1[0]; iPtr1 < endPtr; iPtr1++) { *iPtr1 = *iPtr2; iPtr2 ++; }Note that we can compare two pointers.
int a[10], *iPtr, sum, i; iPtr = &a[0];To access the element of an array,
Similarly, you can access the element through pointer,
*(iPtr + 0), *(iPtr + 1), *(iPtr + 2) , ..., *(iPtr + i)
So the following 2 loops are equivalent:
for(i = 0, sum = 0; i < 10; i++) { sum += a[i]; } for(i = 0, sum = 0; i < 10; i++) { sum += *(iPtr + i); }
If you make the pointer point to an array (or a part of an array), you can treat the pointer as if it were an array.
int a[10]; int *iPtr; iPtr = a + 2;
The last statement is same as
iPrt = &a[0] + 2;or
iPrt = &a[2];
Also you can do the pointer arithmetics with array name. The following statement
*(a + 2) = 11;is equivalent to (surprise, surprise):
a[2] = 11;
You can't copy two arrays in the following way.
int a[10], b[10]; a = b; /* CAN'T DO THIS */
The following is ok:
int *iPtr1, *iPtr2, a[10]; iPtr1 = a; iPtr2 = iPtr1;The two pointers are pointing to the same array. But we haven't copied the data pointed to. In other words, if you modify the value of iPtr1[3] = 15, iPtr2[3] also become ``15'', since they are pointing to the same memory location.
Name of the array is like a ``constant'' pointer. When the array is declared, the memory is allocated, and the array name holds the address to this memory. However, you CANNOT change the value of the ``pointer'' (address) like a regular pointer.
#include <stdio.h> int main(void) { int a[] = {0, 3, 6, 9, 12}; int *iPtr = a + 2; printf("%d %d %d\n", *iPtr, *iPtr - 2, *(iPtr + 1)); }