Pointers, Arrays, Pointers and Arrarys
Q23. Define pointer and explain in detail about it.
Answer :
Pointer
A variable that stores address of another variable is called a ‘pointer’.
Example
int x =2;
This statement will allow the system to locate integer variable ‘x’ and store ‘2’ in that location. If ‘x’ is stored at location '1210' by the system, then address of the variable ‘x’ will be 1210.
Let ‘y’ be another variable stored at location ‘1315’ and ‘1210’ be stored in ‘y’. Since, y stores the address of x, it is a pointer. It is declared as follows,
int *y;
y = 1210;
or
y = &x;
As address of ‘x’ is stored in ‘y’, the value of ‘x’ can be accessed using ‘y’ and is thus said to be a ‘pointer’ to ‘x’.
Declaration of Pointers
Pointers are declared as shown
below,
datatype *ptr;
Here, ‘*’ indicates that ptr is a
pointer variable representing value stored at a particular address.
Example
int *p:
char *q;
float *f;
Here,
‘p’ Points to address location
where an integer type data is stored.
'q' Points to address location
where character type data is stored.
'f ’ Points to address location where float type data is stored.
Initialization of Pointer Variable
Pointer variable can be initialized during declaration as shown below,
int *p;
*p = 5;
When the above statement is compiled, the value 5 is stored in an address pointed by p. Suppose, p points to an address 1540 then, 5 is stored in location 1540.
Here, p is 1540 and *p
gives value 5.
Assigning Address of Variable to Pointer Variables
A pointer variable is used to point to the addresses of other variables.
Example 1
int *p;
int x=5;
p= &x;
Here, address of variable x is assigned to pointer p.
*p gives values at location 1000 i.e., 5 which is same as value of x.
Here, the ‘&’ used is same as the one used in scanf function. The ‘&’ is called “address of’ operator. This is used to assign the address of a variable next to it.
Example 2
int *p = &x;
This statement will transfer the address of x to p.
Note: In the above initialization, the address of x is assigned to p but not *p,
p will point to address of x.
*p will point to value of x.
&p will point to address of p.