VR Indian Wanderers Youtube Facebook RSS Feed
Learn with Vikas Suhag
Dynamic memory allocation in C Language using malloc() function
Mar 06, 2022   Vikas Suhag

#include<stdio.h>
#include<stdlib.h>
int main()
{
    // This pointer will hold the base address of the block created
    int* ptr;
    int n, i;
    
    printf("Enter number of elements:");
    scanf("%d",&n); // Get the number of elements for the array
    printf("Entered number of elements: %d\n", n);
    
    ptr = (int*)malloc(n * sizeof(int)); // Dynamically allocate memory using malloc()
    
    if (ptr == NULL) // Check if the memory has been successfully // allocated by malloc or not
    {
        printf("Memory not allocated.\n");
        exit(0);
    }
    else
    {
        printf("Memory successfully allocated using malloc.\n"); // Memory has been successfully allocated
        for (i = 0; i < n; ++i)
        {
        ptr[i] = i + 10; // Set the elements of the array
        }
        printf("The elements of the array are: "); // Print the elements of the array
        for (i = 0; i < n; ++i)
        {
        printf("%d, ", ptr[i]);
        }
    }    
    return 0;
}

 


Leave a Comment

* Email will not be published.
All comments are only visible after approval.
Most Viewed articles
Travel Blog - VR Indian Wanderers
VR Indian Wanderers
Govt. Jobs Portal
Govt. Jobs Portal
Free Chart Maker
Make free animated Charts from .CSV
Search
Youtube Channel
Podcast
Subscribe to Email Updates
Connect With Us
VR Indian Wanderers Youtube Facebook RSS Feed
© 2024 Learn with Vikas Suhag. All Rights Reserved.