Example C program that uses dynamic memory allocation, Learn dynamic memory allocation
Dynamic memory
allocation
//Program to sum num number of integers by allocating memory
dynamically
#include
<stdio.h>
#include
<stdlib.h> //To be included to use malloc()
function
int
main()
{
int num, i, *ptr, sum = 0;
printf("Enter number of elements:
");
scanf("%d", &num);
/* The function malloc(sizeof(int)) will allocate raw memory for storing something of size equivalent
to an integer value. The following statement allocates memory for storing num numbers. Hence sizeof(int) is
multiplied by num. The (int *) will convert the allocated raw memory for storing integer
values (type casting). */
ptr = (int*) malloc(num *
sizeof(int));
if(ptr == NULL) //if ptr==NULL
means if memory cannot be allocated for some reasons
{
printf("Error! memory not
allocated.");
exit(0); // Close the program
}
printf("Enter elements of array:
");
for(i = 0; i < num; ++i)
{
scanf("%d", ptr + i); //reads the value for summing
sum += *(ptr + i); //the input numbers are added with the variable sum and stored
in sum
printf("%d", ptr+i);
}
printf("Sum = %d", sum);
free(ptr); //To
free the memory occupied by our program. It is not mandatory for our program
getch();
return 0;
}
**************