Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

Write a c program to dynamically allocate memory for an array to store 10 integers

+5 votes
asked Feb 3 by asish sarkar (350 points)

1 Answer

0 votes
answered Feb 3 by sai YTS (140 points)

#include <stdio.h>

#include <stdlib.h>


int main()



    // This pointer will hold the

    // base address of the block created

    int* ptr;

    int n, i;


    // Get the number of elements for the array

    printf("Enter number of elements:");


    printf("Entered number of elements: %d\n", n);


    // Dynamically allocate memory using malloc()

    ptr = (int*)malloc(n * sizeof(int));


    // Check if the memory has been successfully

    // allocated by malloc or not

    if (ptr == NULL) {

        printf("Memory not allocated.\n");



    else {


        // Memory has been successfully allocated

        printf("Memory successfully allocated using malloc.\n");


        // Get the elements of the array

        for (i = 0; i < n; ++i) {

            ptr[i] = i + 1;



        // Print the elements of the array

        printf("The elements of the array are: ");

        for (i = 0; i < n; ++i) {

            printf("%d, ", ptr[i]);




    return 0;


Enter number of elements: 10
Memory successfully allocated using malloc.
The elements of the array are: 1, 2, 3, 4, 5,6,7,8,9,10
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.