forked from seeditsolution/cprogram
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Memory-management-in-c
43 lines (35 loc) · 1.01 KB
/
Memory-management-in-c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <stdio.h>
int main()
{
printf("\n\n\t\tStudytonight - Best place to learn\n\n\n");
int n, i, *ptr, sum = 0;
printf("\n\nEnter number of elements: ");
scanf("%d", &n);
// dynamic memory allocation using malloc()
ptr = (int *) malloc(n*sizeof(int));
if(ptr == NULL) // if empty array
{
printf("\n\nError! Memory not allocated\n");
return 0; // end of program
}
printf("\n\nEnter elements of array: \n\n");
for(i = 0; i < n; i++)
{
// storing elements at contiguous memory locations
scanf("%d", ptr+i);
sum = sum + *(ptr + i);
}
// printing the array elements using pointer to the location
printf("\n\nThe elements of the array are: ");
for(i = 0; i < n; i++)
{
printf("%d ",ptr[i]); // ptr[i] is same as *(ptr + i)
}
/*
freeing memory of ptr allocated by malloc
using the free() method
*/
free(ptr);
printf("\n\n\t\t\tCoding is Fun !\n\n\n");
return 0;
}