int marks[100];
Such a declaration would typically be used if 100 student's marks were to be stored in memory. The moment we make this declaration 200 bytes are reserved in the memory for storing 100 integers in it. However it mayso happen that when we actally run the program, we might be interested in storing only 60 students marks.Even in this case 200 bytes would get reserved in the memory, which would result in wastage of memory.
Other way round there always exist a possibility that when you run the program you need to store more than 100 students marks. In this case the array would fall short in size. Moreover there is no way to increase or decrease the array size during execution of the program. In other words,when we use array, static memory allocation takes place. What if we want to allocate memory only at the time of execution? This is dome using standard library functions malloc() and calloc(). Since these functions allocate memory on the fly(during execution) they are often known as 'dynamic memory allocation functions'. Let us now see a program, which uses the concept of dynamic memory allocation.
#include
main()
{
int n,avg,i,*p,sum=0;
cout<<"Enter the number of students";
cin>>n;
p=(int *)malloc(n*2);
if(p==NULL)
{cout<<"memory allocation unsuccessful";
exit();
}
for(i=0;i
avg=sum/n;
cout<<"average marks"<
Here we have first asked for the number of students whose marks are to be entered and then allocated only as much memory as it is really required to store these marks. Not a byte more, not a byte less. The allocation job is done using the standard library function malloc().malloc() returns a NULL if memory allocation is unsuccessful. If successful it returns the address of the memory chunk that is allocated. We have collected this address in an integer pointer p. Since malloc() returns a void pointer we have typecasted it into a integer pointer. In the first for loop using simple pointer arithmatic we have stored the marks entered form the keyboard into the memory that has been allocated. In the second for loop we have accessed the same values to find the average marks
The calloc()function works exactly similar to malloc() except for the fact that it needs two arguments. for example,
int *p;
p=(int*)calloc(10,2);
Here 2 indicates that we wish to allocate memory for storing integers,(since an integer takes 2 bytes entity) and 10 indicates that we want to reserve space for storing 10 integers. Another minor difference between malloc() and calloc() is that, by default, the memory allocated by malloc() contains garbage values, whereas that allocated by calloc() contains all zeros. While using these functins it is necessary to include the file