Dynamic memory allocation means,
programmer can manually handle memory space during runtime of program. Malloc( ) function allocates
requested size of bytes and returns a pointer to first byte of allocated memory.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr;
//Following statement allocates 2 int size memory space
ptr = (int*)malloc(2*sizeof(int));
if(ptr == NULL)
{
printf("Error during memory allocation.");
exit(0);
}
printf("Enter your number1: ");
scanf("%d", ptr);
printf("Enter your number2: ");
scanf("%d", ptr+1);
printf("Your number1 = %d\n", *ptr);
printf("Your number2 = %d", *(ptr+1));
free(ptr); //allotted memory will be cleared.
return 0;
}
Output of the program:
Enter your number1: 101
Enter your number2: 202
Your number1 = 101
Your number2 = 202
* * * * *
No comments:
Post a Comment