C Introduction
Control Statement
Functions
Array
Pointers
Structure and Union
No Examples found for this topic - CodeHelpPro
Data Files
No Examples found for this topic - CodeHelpPro
Memory Allocation For Pointer
In this example, We will learn a memory management for pointer using malloc. Before that, You must have knowledge of the following topics.
CODE
#include <stdio.h>
int main()
{
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)
{
printf("\n\nError! Memory not allocated\n");
return 0;
}
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\nElements of the array are: ");
for(i = 0; i < n; i++)
{
printf("%d ",ptr[i]);
}
//remove allocate memory using free() method
free(ptr);
return 0;
}
The output of above program is
Enter number of elements: 5
Enter elements of array:
1
2
3
4
5
Elements of the array are: 1 2 3 4 5
Subscribe
Login
0 Comments
Inline Feedbacks
View all comments