Overview of Pointers
When variables are declared, memory is allocated to each variable
C provides data manipulation with the addresses of the variables, therefore execution time is reduced.
Such concept is possible with special data type called pointer.
In order to locate Ashok in the HOSTEL, refer to the room no. 101.
Similarly, in the memory every variable has its own address (1001 for ‘10’ and 1002 for ‘a’ and so on) as shown in the above figure.
‘Pointer’ is a variable which holds address of another variable.
Example
int var;
int *ptr;
*ptr = &var;
Which returns the address of ‘var’.
Example 1:
A normal variable ‘var’ has a memory address of 1004 and holds a value 10.
A pointer variable has its own address 1047 but stores 1004, which is the address of the variable ‘var’.
Example 2:
‘k’ is the name of the memory location name and value in ‘k’ is 5 and
If we say ‘&k’ then the address of ‘k’ will be return i.e., ‘64525’.
Example 3
‘i’ is the name given for particular memory location
Consider its corresponding address be 61125 and the value stored in variable ‘i’ is 5.
The address of the variable ‘i’ is stored in another integer variable whose name is ‘j’ and which is having corresponding address 62555.
If we say j=&i;
Variable name
|
Variable value
|
Variable address
|
i
|
5
|
61125
|
j
|
61125
|
62555
|
Example 4
Example 5
int a=13;
int *ptr;
ptr=&a;
Explanation:
About variable a:
Name of variable: a
Value of variable which it keeps: 13
Address where it has stored in memory: 3006
About variable ptr:
Name of the variable: ptr
Value of variable which it keeps 3006
Address where it has stored in memory: 5000
Note:
A variable where it will be stored in memory is decided by operating system. We cannot guess at which location a particular variable will be stored in memory.