Monday, February 22, 2025

Add two number using pointer and Dynamic memory allocation




Add two number using pointer and Dynamic memory allocation
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
void main()
{
int *ptr,sum=0,i;
clrscr();
// 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);
getch();
}

Better Version :(If At Run Memory is not available then It Will Return NULL)
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
void main()
{
int *ptr,sum=0,i;
clrscr();
// 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("Enter number : ");
     scanf("%d",ptr);
     sum = sum + (*ptr);
     }
printf("\nSum = %d",sum);
getch();
}

Output :
Enter number : 4
Enter number : 5
Sum = 9

Tags / Keywords : | , ,

Stumble
Delicious
Technorati
Twitter
Facebook

3 Comments:

RIKKI said...

C is all about portability, next time keep that in mind.

Never assume your functions to be successful, waste a few clock cycles to check the status of your function.

Anonymous said...

Keep posting stuff like this i really like it

c4learn Author said...

@RIKKI & Anonymous
Thanks for Commenting Contact me at c4learn.contact@gmail.com if you have any suggestion .No one is perfect so feel free to suggest any changes .

Post a Comment

Your Feedback :This is Growing Site and Your Feedback is important for Us to improve the Site performance & Quality of Content.Feel Free to contact and Please Provide Name & Contact Email

 

Learn C Programming Copyright © 2010 LKart Theme is Designed by Lasantha, Free Blogger Templates