What is a pointer?
In Computer Programming, a pointer is a derived variable that contains the memory address of another variable that means it points another variable. Pointer can point both pointer variable and normal variable. When it points to another pointer variable, it is called pointer of pointer or chain of pointer and when it points to a variable, it is called pointer of variable. Pointer is built from the fundamental data type in C.
Why should we learn or use pointer?
Pointer is the most interesting and powerful feature of C languages. We should use pointer for the reason below:
1. Since pointer can contain the memory address of another variable, it can access and manipulate what (data) stored in memory.
2. Pointer leads to maximum efficient and executable code than can be obtained in other ways.
3. Since Pointer and Array are closely related with each other, so it is more efficient to handle arrays and data tables with using pointer in those.
4. To return multiple values from a user defined function with arguments, pointer is more efficient.
5. Pointer can be used to access the dynamic memory management (allocation, reallocation of memory for variable).
6. To reduce the size, time complexity or execution time of program and increase execution speed of program pointer is the most efficient tools.
7. To manipulate dynamic data structure (struct, trees, stacks, linked lists, queues), pointer is efficient tool.
Basic of pointer:
Before understanding the basic concept of pointer we must understand the organization of memory in computer system. In the computer, memory is organized consecutively in array of cell and addressed that may be manipulated individually or in groups. It is started from zero and continue sequentially.
|Figure: Organization of Memory in Computer System|
Here, 0…..50000, 50001, 50002, 50003, …. 65554 are memory addresses of different memory cell.
When we declare a variable and try to execute the computer system allocates some spaces in the memory. If we put something that is a single byte, the system will allocate a unique memory address number.
Example of pointer:
From the above figure, let compromath is a variable that has been declared and the system has allocated a unique memory address number and it is 50000. Again let cpm is another variable but pointer that has been declared and 65552 is the unique memory address number of it.
If we point compromath by cpm then cpm will hold the address of compromath. For that the value of cpm will return the value of compromath.