Let me first give an example and then explain it.
#include <stdio.h>
int main()
{
int arr[4] = {11, 34, 71, 2};
int *p;
printf("Array arr is %d %d %d %d\n", arr[0], arr[1], arr[2], arr[3]);
printf("Address of arr[0] is %p\n", &arr[0]);
printf("Address of arr[1] is %p\n", &arr[1]);
printf("Address of arr[2] is %p\n", &arr[2]);
printf("Address of arr[3] is %p\n", &arr[3]);
p = &arr[0];
printf("Pointer p address is %p value is %d\n", p, *p);
p = &arr[2];
printf("Pointer p address is %p value is %d\n", p, *p);
p++;
printf("Pointer p address is %p value is %d\n", p, *p);
p-=3;
printf("Pointer p address is %p value is %d\n", p, *p);
/* Accessing the whole array using pointer */
printf("Using p arr value is %d %d %d %d\n", *p, *(p+1), *(p+2), *(p+3));
/* Accessing whole array using p and array notation */
printf("Using p (index notation) arr value is %d %d %d %d\n", p[0], p[1], p[2], p[3]);
/* Using arr with pointer notation*/
printf("arr value using pointer notation is %d %d %d %d\n", *arr, *(arr+1), *(arr+2), *(arr+3));
return 0;
}
Array arr is 11 34 71 2
Address of arr[0] is 0xbf90dbcc
Address of arr[1] is 0xbf90dbd0
Address of arr[2] is 0xbf90dbd4
Address of arr[3] is 0xbf90dbd8
Pointer p address is 0xbf90dbcc value is 11
Pointer p address is 0xbf90dbd4 value is 71
Pointer p address is 0xbf90dbd8 value is 2
Pointer p address is 0xbf90dbcc value is 11
Using p arr value is 11 34 71 2
Using p (index notation) arr value is 11 34 71 2
arr value using pointer notation is 11 34 71 2
Lessons learnt from the above program
- &arr[0] is address of a integer, hence it can be assigned to integer pointer.
- Pointer arithmetic makes so much sense when it comes to array.
- ++ increment of the pointer makes it to point to next element of the array.
- Other short hand operator can be used with pointer to move though the array very easily.
- Pointer and array notation are interchangeable.
- Array can used with pointer notation, e.g *(arr+2) so on.
- Pointer can be used with array notation, e.g. p[2].
- NOTE array and pointer are very different.
- sizeof(arr) would return 16 (assuming int is 4 bytes), while the sizeof(p) is always 4 (assuming 32 bit machine).
- Pointer can point to different array. e.g. p = &brr[0];, But same cannot be done to array.
- Address of the array is fixed and cannot be changed.
Links
Next Article - C Programming #49: Pointer to arrayPrevious Article - C Programming #47: Array of pointers
All Article - C Programming
No comments :
Post a Comment