C PROGRAMMING PROGRAM • POINTERS & DYNAMIC MEMORY

Sort a Dynamically Allocated Array

Learn how to sort a dynamically allocated array using a clear C program.

Intermediatemalloc()Pointer indexingBubble sort

PROBLEM UNDERSTANDING

Input and expected output

Sample input
5
9 2 7 1 4
Sample output
Sorted: 1 2 4 7 9

COMPLETE C PROGRAM

Complete C implementation

sort-dynamic-array.c
Open in compiler
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    size_t count;
    printf("Enter array size: ");
    scanf("%zu", &count);
    int *values = malloc(count * sizeof *values);
    if (values == NULL && count != 0) return 1;
    printf("Enter elements: ");
    for (size_t index = 0; index < count; index++) scanf("%d", &values[index]);
    for (size_t pass = 0; pass < count; pass++)
        for (size_t index = 0; index + 1 < count - pass; index++)
            if (values[index] > values[index + 1]) {
                int temporary = values[index];
                values[index] = values[index + 1];
                values[index + 1] = temporary;
            }
    printf("Sorted: ");
    for (size_t index = 0; index < count; index++) printf("%d ", values[index]);
    putchar('\n');
    free(values);
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

Sorted: 1 2 4 7 9
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Allocate exactly the requested storage, sort through indexed pointer access, then free it.
  3. Display the computed result.

Allocate exactly the requested storage, sort through indexed pointer access, then free it.

EFFICIENCY

Time and space complexity

Time complexity

O(n²)

Auxiliary space

O(n)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.