Memory Allocation For Pointer

0 June 15, 2021

In this example, We will learn a memory management for pointer using malloc. Before that, You must have knowledge of the following topics.

Download Application: Learn C Programming with Live Compiler

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
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Join Our Newsletter Now

Get the latest tutorials, examples and projects updates.

Ads Block Detector Powered by codehelppro.com

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Disable Ad Block

Want Same System