1 #include <stdio.h>
2 int main(void){
3 int urn[5] = { 100, 200, 300, 400, 500 };
4 int *ptr1, *ptr2, *ptr3;
5
6 ptr1 = urn;//assign a address to a piontor
7 ptr2 = &urn[2];//dereferenced a pointor and take the address of a pointor
8 printf("ptr1 = %p, *ptr1 =%d, &ptr1 = %p
", ptr1, *ptr1, &ptr1);
9
10 ptr3 = ptr1 + 4;
11 printf("ptr1 + 4 = %p, *(ptr1 + 3) = %d
", ptr1 + 4, *(ptr1 + 3));
12 ptr1++;
13 printf("ptr1 = %p, *ptr1 = %d, &ptr1 = %p
", ptr1, *ptr1, &ptr1);
14
15 ptr2--;
16 printf("ptr2 = %p, *ptr2 = %d, &ptr2 = %p
", ptr2, *ptr2, &ptr2);
17
18 --ptr1;
19 ++ptr2;
20 printf("ptr1 = %p, ptr2 = %p
", ptr1, ptr2);
21
22 printf("ptr2 = %p, ptr1 = %p, ptr2 - ptr1 = %ld
", ptr2, ptr1, ptr2 - ptr1);
23 printf("ptr3 = %p, ptr3 - 2 = %p
", ptr3, ptr3 - 2);
24
25 return 0;
26 }
Remeber:
1 Assignment: you can assign an address to a pionter.
Do not dereference an uninitialized pointer..for example, int *pt; *pt = 5.(correct : int *pt; int a = 5; pt = &a;)
2 value finding(dereferencing)
3 Taking a pointer address: Like all variables, a pointer variable has an address and a value.
4 Adding an integer to a pionter: the integer is multiplied by the number of bytes in the pointed-to type, and the result is added to the original address.
5 Incrementing a pointer: Incrementing a pointer to an array element makes it move to the next element of the array.
6 Subtracing an integer from a pointer
7 Decrementing a pointer
8 Differencing (ptr2 - ptr1)