C adding numbers using pointer & malloc()



Add two number using pointer and Dynamic memory allocation

In this program , we have not declared two variables at compile time. We are going to accept values at run time by allocating memory at run time.

#include<stdio.h>
#include<stdlib.h>
int main()
{
int *ptr,sum=0,i;
// Allocate memory Equivalent to 1 integer
ptr = (int *)malloc(sizeof(int));
for(i=0;i<2;i++)
    {
    printf("Enter number : ");
    scanf("%d",ptr);
    sum = sum + (*ptr);
    }
printf("nSum = %d",sum);
return(0);
}

In the above program we have considered that , Memory will be available at any moment of time. Now Suppose Memory is unavailable at run time then we are unable to allocate memory. Executing dynamic memory allocation function would cause System Crash.

#include<stdio.h>
#include<stdlib.h>
int main()
{
int *ptr,sum=0,i;
// Allocate memory Equivalent to 1 integer
ptr = (int *)malloc(sizeof(int));
if(ptr==NULL)
    {
    printf("\nError in Allocating Memory");
    exit(0);
    }
for(i=0;i<2;i++)
    {
    printf("\nEnter number : ");
    scanf("%d",ptr);
    sum = sum + (*ptr);
    }
printf("\nSum = %d",sum);
return(0);
}

Output :

Enter number : 4
Enter number : 5
Sum = 9

Explanation of the Program :

Suppose memory is unavailable at run time then it will return NULL. We are checking the value of pointer with NULL. If legal address is provided by calloc or malloc then we can consider that memory is allocated successfully , however if these memory allocation functions return NULL then we can say that some error occurred while allocating memory.

if(ptr==NULL)
    {
    printf("\nError in Allocating Memory");
    exit(0);
    }

We don’t have access to the first number once we accepted 2nd number. However we can store address of First Number as soon as after allocation.

for(i=0;i<2;i++)
    {
    printf("\nEnter number : ");
    scanf("%d",ptr);
    sum = sum + (*ptr);
    }