In the program shown below, the first and last elements of an integer array are pointed by two different pointer variables.
#include < stdio.h >
main()
{
int *px, *py; /*integer pointers*/
static int a[6] = {1, 2, 3, 4, 5, 6};
px = &a[0];
py = &a[5];
printf("px=%X py=%X", px, py);
printf("\n\npy - px=%X ", py-px);
}
Execution of the program results in the following output
px=52 py=5C
py - px=5
The first line indicates that addresses of a[0] and a[5] are 52 and 5C respectively.The difference between these two hexadecimal numbers is 10 (converted to decimal).
The permissible operations on pointers are summarized below:
1. The address of an ordinary variable can be assigned to a pointer variable (e.g, pv=&v).
2. The value of a pointer variable can be assigned to another pointer vatiable (e.g., pv=px) provided both pointers point to objects of the same data type.
3. A null (zero) value can be assigned to a pointer variable (e.g., pv=NULL, NULL--->symbolic constant that represent the value 0).
4. An integer quantity can be added or subtracted from a pointer variable (e.g., pv+3, ++pv etc.).
5. One pointer variable can be subtracted from another provided both pointers point to the elements of the same array.
6. Two pointer variables pointing to objects of the same data type can be compared.
Other arithmetic operations on pointers are not allowed.Thus, a pointer variable cannot be multiplied by a constant;two pointer variables cannot be added and so on.
No comments:
Post a Comment