Dynamic memory allocation is a technique in which programs determine as they are running where to store some information. You need dynamic allocation when the amount of memory you need, or how long you continue to need it, depends on factors that are not known before the program runs.
ptr=(cast-type*)malloc(byte-size)
#include<stdio.h> #include<stdlib.h> int main() { int i,length,sum=0; printf(" Enter the count of numbers:"); scanf("%d", &length); int *p; p=(int*) malloc((sizeof(int)*length); for(i=0; i<length;i++) { printf("Enter a number :"); scanf("%d",p+i); } for(i=0; i<length;i++) { sum=sum+*(p+i); } return 0; }
After using malloc() function memory must be restored using de-allocation. The memory has to be de-allocated to efficiently use the memory space. So, to free up the memory allocated, use free() function. Then that freed space is ready to use again
#include<stdio.h> #include<stdlib.h> int main() { int i,length,sum=0; printf(" Enter the count of numbers:"); scanf("%d", &length); int *p; p=(int*) malloc((sizeof(int)*length); for(i=0; i<length;i++) { printf("Enter a number :"); scanf("%d",p+i); } for(i=0; i<length;i++) { sum=sum+*(p+i); } return 0; }
ptr=(cast-type*)calloc(number, byte-size)
#include<stdio.h> #include<string.h> #include<stdlib.h> int main() { int length,i; int *ptr; printf("Enter count of number:"); scanf("%d",&length); ptr=(int*)calloc(length,sizeof(int)); if(ptr==NULL) { printf("Cannot allocate memory"); exit(1); } for(i=0;i<length;i++) { printf("Enter a number %d: ",i); scanf("%d",&ptr[i]); } for(i=0;i<length;i++) { printf("Enter a number %d: ",i); scanf("%d",ptr[i]); } return 0; }