Declaration
of Pointer: Part 2
The Two fundamental operators used with the
pointers are:
1.
Address
operator &
2.
Indirection
operator *
#include<stdio.h>
void main()
{
Int a=5;
Int *p; /*Pointer declaration*/
P=&a; /*copying address of
variable to the pointer p */
*p =10; /* use of pointer to
change the value of variable a*/
printf(“%d”, a);
printf(“%d”, *p);
printf(“%d”, *(&a));
}
All the printf statements in the above program will give the output as
10
Memory and Pointer
int *p1;
float *p2;
char *p3;
all pointers p1, p2, p3 get 2 bytes each.
Suppose if three pointers are declared for int, float, char. All the
three pointers will occupy 2 bytes in the memory. This is because all the
memory addresses are integer values ranging from 0 to 65536.
Example
Void main()
{ int a=5, *p1;
Float b=2.5, *p2;
Char c=’a’, *p3;
p1=&a;
p2=&b;
p3=&c;
printf(“%d”, sizeof(p1));
printf(“%d”, sizeof(p2));
printf(“%d”,sizeof(p3));
}
Output 2 2 2
Pointers and Address:-
Void main(){
Int a=5;
Int *p;
P =&a;
Printf(“%p”,p); //print the actual address of pointer//
Printf(“%d”,p); //print the address in integer formata //
Printf(“%u”,p); //print the address of pointer p as unsigned integer //
Printf(“%X”, p); // print the address of pointer p as
hexadecimal //
}
Output:
fff4, -12, 65524, FFF4
Let us evaluate the output the
first answer using %p is print the actual address of pointer which is fff4.
Second answer is a negative value this is because the range of pointers if from
0 to 65536 and variable are allocated memory from top to bottom i.e. from 65536
then 65535, 65534 and so on until 0.
Third
answer is 65524 that means if we convert fff4 (hexadecimal) into decimal we get
65524 and difference of bottom to top (655524 – 65536 = -12) that’s why we will
get second answer into integer.
The last
answer is hexadecimal into capital %X which is FFF4.
Pointers Expression:-
Like any
other variable, pointer variables can be used in expression.
1.
C
allows us to add or subtract integers from pointers.
Ex. Sum = sum + *p1;
Ex. *p3 = *p1 + *p2
Ex. Result = 50 - *p1;
Ex. Ans = *p1 + *p2++;
2.
Two
Pointers can not be multiplied and divided.
3. Declaration
with array:
Void
main()
{
Int a[5]={10,20,30,40,50};
Int *p;
p=a //address of array can be
pointed into the pointer without the use of & operator //
printf(“%d”,*p); //10
printf(“%d”,*(p+1)); //20
printf(“%d”, *(p+2)); //30
printf(“%d”, *(p+3)); //40
printf(“%d”, *(p+4)); //50
getch();
}
Pointers
store the address of a variable, similarly the address of a pointer can also be
stored in some other pointer.
Void main()
{
Int a=5;
Int *p1; // pointer to an integer :single pointer
Int **p2
// pointer to pointer to an integer:
Int ***p3 // pointer to pointer to pointer to an
integer : Triple pointer
P1=&a;
P2=&p1;
P3=&p2;
Printf(“%d”,a)
// 5
Printf(“%d”,*p1) //5
Printf(“%d”,**p2)
//5
Printf(“%d”,
***p3) //5
}
No comments:
Post a Comment