Pointers in C

Let us start with this  ->


Why pointers ?


  • You would have studied functions.There you may have seen the drawback of the return statement that it can return only 1 value .Pointers help to overcome this flaw.
  • Imagine a scenario where you have to use an array.But you don’t know how much size would be required at runtime , so you allocate a sufficiently large size to your array at compile time.Suppose at runtime only half of the size of this array is required.Then half of your memory is wasted.So,pointers support Dynamic Memory allocation (DMA) which would help you to overcome the memory wastage problem.

What is a pointer ?

Any variable that stores address of any other variable.
Representation : type* ptr ;
ptr is name of the pointer variable and type refers to the address of which type of variable it is going to hold.The datatype of ptr is type*
A simple example :
Lets have a look at below snippet
    int a=300;
    int* ptr=&a;             //& operator is used to retrieve address of a variable
    printf("%p",ptr);        /*format specifier p is used for printing hexadecimal address 
                              of memory location of a  */
ptr stores address of a. a is an integer variable,so any pointer which has to hold address of    a   should be of type int*
As ptr stores address of a ,we say that ptr points to a .In the above snippet we have printed the address of a using ptr.
Now how  to print value of    a     using ptr. So here’s how we go
printf("%d",*ptr);
operator * is used to retrieve value at a memory location.ptr is holding a’s address(memory location).So value at this address would be retrieved.So the picture would be like given below
              a           ptr            *ptr
Address   0xbfae01b8   0xbfae01bc      0xbfae01b8

Value       300        0xbfae01b8        300
Above,note that address of a and *ptr is same.How would you print address of *ptr ?By prefixing an & operator i.e &*ptr
Now *ptr = value at memory location that ptr holds = value at a’s address =  a
So  &*ptr = &a

Uses of pointers



1. Overcoming the problem of return statement that can return only one value from a function
For this,we use pass by address mechanism.We pass the addresses of variables to functions and we don’t have to return anything from the function as changes are made on the actual addresses.
Lets look at an example to accept radius and calculate area of circle in an function and you have to print both radius and calculated area in main().Now return would not work here because we can’t return more than 1 value from function.
So we use Pass by address mechanism
#include <stdio.h>

void acc_calc(float*,float*);

int main(void) 
{
    float rad,area;
    acc_calc(&rad,&area);
    printf("\nRadius = %.2f\nArea = %.2f",rad,area);
    return 0;
}

void acc_calc(float* prad,float* parea)
{
    printf("Enter radius ");
    scanf("%f",prad);
    *parea = 3.14 * (*prad) * (*prad); 
}
If we would have passed rad and area by value then values of both are copied in different memory locations and changes are made on this local copies.So changes are not reflected in main.But if you pass by address then the picture is as shown below

             rad          area        prad          parea
Address   0xbf9f2cf8    0xbf9f2cfc

Value                               0xbf9f2cf8    0xbf9f2cfc
So ,by changing *prad and *parea , we are directly changing contents at memory location of main() ‘ s rad and area .So, we are not required to return anything as changes are directly reflected in main().
2. Overcoming the memory wastage problem
Suppose we are sorting elements and how many elements to sort would be entered by user.We will declare an array of size n but at runtime user said he just wants to sort (n/2) elements and eventually 1/2 of the memory was wasted as u declared an memory to store n elements at compile time.
So for this you can use pointers.By pointers , you can allocate memory at runtime.Here’s a quick syntax of how you do it

arr = malloc(n*sizeof(int));
malloc is an inbuilt function to allocate memory dynamically.malloc would allot a n*sizeof(int) bytes block of memory.
So , now arr is pointing to the block of memory allocated by malloc.


Disadvantages of pointers


  • Pointers can be used for DMA.In this case,memory needs to be freed explicitly or it can lead to memory leakage.
  • If pointers are not initialized ,they may cause segmentation fault.

There are many applications of pointers as they are used to implement complex data structures like linked list,trees,etc.


More

No comments:

Post a Comment