C Program: Dynamic Array of Integers and Sum
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program to Dynamically Allocate Memory for an Array of Integers and Display the Sum of All Elements

📑 On this page:
  • Objective & Purpose
  • What is Dynamic Memory Allocation?
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Key Takeaways
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How to allocate memory at runtime with malloc()
  • How to check for a NULL return and handle allocation failure
  • How to read elements into a dynamically allocated array
  • How to accumulate the sum of all elements
  • How to release memory with free() to avoid leaks

Objective & Purpose

Objective: The fundamental objective of this program is to show how to dynamically allocate memory for an array of integers in C and to compute the sum of all elements in that array.

Purpose: This program explains the concept of dynamic memory allocation in C and how it is used to work with arrays of integers. With dynamic memory allocation, a program can adjust the size of an array at runtime, making it more flexible and effective.

💡 Quick Definition: Dynamic Memory Allocation (DMA) means asking the operating system for memory at runtime using functions like malloc(), calloc(), realloc(), and returning it with free().

Real-life applications of dynamic memory allocation include managing large data sets, implementing data structures such as linked lists and trees, and optimizing memory utilization in resource-constrained environments.

C program to dynamically allocate memory for an array of integers and display the sum of all elements

What is Dynamic Memory Allocation?

In C, static arrays have a fixed size determined at compile time. If you don't know how many elements you'll need until the program runs, you need dynamic memory.

The malloc() function (from <stdlib.h>) requests a contiguous block of bytes from the heap and returns a void * pointer to it. You then cast it to the appropriate type. If allocation fails (out of memory), malloc returns NULL — always check for that.

Function Signature Purpose
mallocvoid *malloc(size_t bytes)Allocates an uninitialized block of bytes
callocvoid *calloc(size_t n, size_t size)Allocates n × size bytes and zero-initializes
reallocvoid *realloc(void *ptr, size_t size)Resizes an existing block
freevoid free(void *ptr)Releases a block back to the OS

Complete C Program

Program: Dynamically allocate an array of integers and display the sum

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int size, i, *arr, sum = 0;

    /* ask the user for the array size */
    printf("\nEnter the size of the array: ");
    scanf("%d", &size);

    /* allocate memory dynamically */
    arr = (int *)malloc(size * sizeof(int));

    /* check whether allocation succeeded */
    if (arr == NULL)
    {
        printf("\nUnable to allocate memory!\n");
        return 1;
    }

    /* read the elements */
    printf("\nEnter %d elements:\n", size);
    for (i = 0; i < size; i++)
    {
        scanf("%d", &arr[i]);
    }

    /* compute the sum of all elements */
    for (i = 0; i < size; i++)
    {
        sum += arr[i];
    }

    /* display the result */
    printf("\nThe sum of all elements in the array is = %d\n", sum);

    /* release the memory */
    free(arr);
    arr = NULL;

    return 0;
}
                                    

Program Output

Enter the size of the array: 5

Enter 5 elements:
11
12
13
14
15

The sum of all elements in the array is = 65
                                

Step-by-Step Explanation

Let's break down this program line by line to understand what's happening:

1. Inclusion of header files:

#include <stdio.h>
#include <stdlib.h>
                                

stdio.h gives us printf and scanf. stdlib.h gives us malloc and free.

2. Variable Declaration:

int size, i, *arr, sum = 0;
                                

size holds the number of elements, i is the loop counter, *arr will point to the heap block, and sum starts at 0. The loop counter is declared up front so the code stays C89-compatible.

3. Ask the user for the size:

printf("\nEnter the size of the array: ");
scanf("%d", &size);
                                

The size is not known at compile time — this is exactly why we need dynamic allocation.

4. Allocate memory with malloc:

arr = (int *)malloc(size * sizeof(int));
                                

size * sizeof(int) calculates the total number of bytes needed. On most platforms sizeof(int) == 4, so for 5 elements we ask for 20 bytes. The cast (int *) converts the void * returned by malloc into an int *.

5. Check for NULL:

if (arr == NULL)
{
    printf("\nUnable to allocate memory!\n");
    return 1;
}
                                

If malloc couldn't allocate the block, it returns NULL. Using a NULL pointer is undefined behavior — so we bail out gracefully instead.

6. Read elements into the array:

for (i = 0; i < size; i++)
{
    scanf("%d", &arr[i]);
}
                                

arr[i] is pointer arithmetic — arr[i] is equivalent to *(arr + i). The & gives the address of each element for scanf.

7. Compute the sum:

for (i = 0; i < size; i++)
{
    sum += arr[i];
}
                                

sum += arr[i] is the compound form of sum = sum + arr[i]. For elements 11, 12, 13, 14, 15 the running total becomes 11 → 23 → 36 → 50 → 65.

8. Display the result and free the memory:

printf("\nThe sum of all elements in the array is = %d\n", sum);
free(arr);
arr = NULL;
                                

free(arr) returns the heap block to the operating system. Setting arr = NULL afterward prevents accidental use-after-free bugs.

Key Takeaways

Rule Why it matters
Always check malloc for NULLPrevents crashes on low-memory systems
Match every malloc with a freePrevents memory leaks
Set pointers to NULL after freePrevents dangling pointers
Use n * sizeof(type), not hardcoded numbersPortable across platforms
Never dereference the return value of malloc before checking itAvoids undefined behavior

🎯 Key Takeaway: Dynamic memory problems are not hard because of the logic — they're hard because of lifecycle discipline. Allocate → check → use → free. Follow that order and you'll never leak memory.

Frequently Asked Questions

1. Why do we need dynamic memory for this array?

Because the number of elements isn't known until runtime. A fixed-size array would either be too small (causing errors) or waste memory.

2. What happens if malloc returns NULL?

If allocation fails, malloc returns NULL. Dereferencing a NULL pointer crashes the program. This is why every malloc call must be checked.

3. Do I need to cast the result of malloc?

In C, it's not strictly required — void * implicitly converts to any pointer type. But casting (int *)malloc(...) is common practice and keeps the code compatible with C++ compilers.

4. What if I forget to call free()?

You get a memory leak. The program keeps the block reserved until it exits. For long-running programs (servers, daemons), leaks accumulate and eventually exhaust memory.

💡 Tip: Compile with gcc -fsanitize=address -g program.c to catch leaks and use-after-free bugs instantly.

📖 Related Tutorials

  • malloc in C
  • calloc in C
  • realloc in C
  • free in C
  • DMA Examples in C
  • All DMA Assignments

Previous Topic: -->> Storage Class Assignments in C   ||   Next topic: -->> 2. Reverse a Dynamically Allocated String


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processing
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.