malloc() - Dynamic memory allocation function
The process of allocating memory at program run time is known as dynamic memory allocation. Following program will dynamically allot space as per user requirement.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, n;
int *myspace;
printf("Enter total numbers to be stored: ");
scanf("%d", &n);
/*Following statement will allot n blocks of int in memory.
malloc returns a void pointer; then it is type-casted to (int*).
myspace points to the first block of the newly allocated space.
*/
myspace = (int*) malloc(n*sizeof(int));
//It returns NULL pointer, if fails to allocate enough space.
if(myspace == NULL)
{
printf("Error!!! Space problem..");
exit(0);
}
//Logic to store numbers to dynamically allocated space
for(i=0; i<n; i++)
{
printf("Enter number %d:",i+1);
scanf("%d", myspace+i);
}
//Logic to print numbers from dynamically allocated space
printf("\n%d numbers stored in dynamically allotted space:\n", n);
for(i=0; i<n; i++)
{
printf("%d ", *(myspace+i));
}
return 0;
}
Output of program
Enter total numbers to be stored: 5
Enter number 1:2
Enter number 2:4
Enter number 3:6
Enter number 4:8
Enter number 5:10
5 numbers stored in dynamically allotted space:
2 4 6 8 10
No comments:
Post a Comment