What are usage of pointers?

Pointers are mainly used for two purposes

1. Indirect Memory Referencing
2. Dynamic Memory Allocation

Indirect Memory Referencing

It allows to read and update the value at some address using indirection operator *

Example of Indirect Memory Referencing

main()
{
    int a=5,b=6;
    int *p=&a;
    *p=2; //value at the address i.e. a is now 2
    p=&b;
    *p=3; //value at the address i.e. b is now 3
    printf("%d %d",a,b);
}

Direct Memory Allocation
We can allocate the dymanic memory on demand which we cannot do with arrays
C provides built-in functions under malloc.h for dymamic memory management

1. malloc()  -- allocate any amount of memory in one go
2. calloc()  -- allocate memory upto 64KB as one by one
3. realloc() -- to change the size of allocated memory.
4. free()  -- to deallocate the allocated memory


Syntax of malloc()
datatype *ptr=(datatype *) malloc(n * sizeof(datatype));
datatype *ptr=(datatype *) calloc(n, sizeof(datatype));

 Example
 WAP to ask the user, how many numbers to input. Input that much of numbers and show sum of all given values.

 Solution 1
main()
{
    int *p,n,i,sum=0;
    printf("How many numbers to input : ");
    scanf("%d",&n);
    p=(int *) malloc (n * sizeof(int)); //dynamic memory allocation
    printf("Enter %d numbers : ",n);
    for(i=0;i<n;i++)
     scanf("%d",&p[i]);
   
    for(i=0;i<n;i++)
     sum=sum+p[i];
    printf("Sum is %d",sum);
}

Solution 2
main()
{
    int *p,n,i,sum=0;
    printf("How many numbers to input : ");
    scanf("%d",&n);
    p=(int *) malloc (n * sizeof(int)); //dynamic memory allocation
    printf("Enter %d numbers : ",n);
    for(i=0;i<n;i++)
     scanf("%d",p+i);
   
    for(i=0;i<n;i++)
     sum=sum+ *(p+i);
    printf("Sum is %d",sum);
}

Relationship between array and pointer
 p[i] --> *(p+i) --> *(i+p) --> i[p]


main()
{
    int ar[]={5,6,7,8};
    int i;
    for(i=0;i<4;i++)
     printf("%d ",ar[i]);
    printf("\n");
    for(i=0;i<4;i++)
     printf("%d ",*(ar+i));
    printf("\n");
    for(i=0;i<4;i++)
     printf("%d ",i[ar]);
    printf("\n");
}








Comments

Popular posts from this blog

What is template?

Can we access private members of an instance?

What are wrapper classes in Java?