C PROGRAMMING PROGRAM • POINTERS & DYNAMIC MEMORY
Expand a Dynamic Array Using realloc()
Learn how to expand a dynamic array using realloc() using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
3 10 20 30 2 40 50
Sample output
10 20 30 40 50
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int initialSize, extraSize;
scanf("%d", &initialSize);
if (initialSize < 1 || initialSize > 1000) return 1;
int *values = malloc((size_t) initialSize * sizeof *values);
if (values == NULL) return 1;
for (int index = 0; index < initialSize; index++) scanf("%d", &values[index]);
scanf("%d", &extraSize);
if (extraSize < 0 || initialSize + extraSize > 2000) { free(values); return 1; }
int *expanded = realloc(values, (size_t) (initialSize + extraSize) * sizeof *values);
if (expanded == NULL) { free(values); return 1; }
values = expanded;
for (int index = initialSize; index < initialSize + extraSize; index++) scanf("%d", &values[index]);
for (int index = 0; index < initialSize + extraSize; index++)
printf("%d%c", values[index], index == initialSize + extraSize - 1 ? '\n' : ' ');
free(values);
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
10 20 30 40 50
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Store realloc() in a temporary pointer, verify success and then continue using the expanded block.
- Display the computed result.
Store realloc() in a temporary pointer, verify success and then continue using the expanded block.
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.
