Dynamic Memory Allocation (malloc)

Algorithm

Step 1: Start

Step 2: Declare integers n, i, *ptr, sum

Step 3: Prompt user to enter the number of elements

Step 4: Allocate memory using malloc

Step 5: Check if memory allocation was successful

Step 6: If not, display error and exit

Step 7: Input elements into dynamically allocated array

Step 8: Calculate sum of array elements

Step 9: Display the elements and the sum

Step 10: Free the allocated memory

Step 11: End

Flowchart

graph TD; A([Start]) --> B[Declare variables]; B --> C[/"Input number of elements (n)"/]; C --> D[Allocate memory using malloc]; D --> E{"Memory allocation successful?"}; E -->|No| F[/Print error and exit/]; E -->|Yes| G[/Input array elements/]; G --> H[Calculate sum of elements]; H --> I[/Print array and sum/]; I --> J[Free memory]; J --> K([End]); classDef start fill:#00cc44,stroke:#006622,stroke-width:2px,color:#ffffff; classDef stop fill:#ff4444,stroke:#cc0000,stroke-width:2px,color:#ffffff; classDef io fill:#ffdd44,stroke:#cc9900,stroke-width:2px,color:#000000; classDef process fill:#4488ff,stroke:#0044cc,stroke-width:2px,color:#ffffff; classDef decision fill:#ff8844,stroke:#cc4400,stroke-width:2px,color:#ffffff; class A,K start,stop; class B,D,H,J process; class C,I,G io; class E decision; class F io;

Program

/* Program for Dynamic Memory allocation using malloc function */
#include <stdio.h>
#include <stdlib.h>

int main() {
    int n, i, *ptr, sum = 0;
    printf("Enter number of elements: ");
    scanf("%d", &n);

    ptr = (int*) malloc(n * sizeof(int));
    if (ptr == NULL) {
        printf("Sorry! unable to allocate memory");
        exit(0);
    }

    printf("Enter elements of array: ");
    for (i = 0; i < n; i++) {
        scanf("%d", ptr + i);
        sum += *(ptr + i);
    }

    printf("\nSum of");
    for (i = 0; i < n; i++) {
        printf("\n %d", *(ptr + i));
    }

    printf("\n------");
    printf("\n %d", sum);

    free(ptr);
    return 0;
}
        
Test Case Output
Enter number of elements: 4
Enter elements of array: 10 20 30 40

Sum of
 10
 20
 30
 40
------
100