Dynamic Array Resizing
Demonstrates dynamic memory allocation and resizing of an array using malloc and realloc.
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("INSTRUCTIONS: Enter initial array size and elements, then new size to resize.\n");
int *array, size, new_size, i;
printf("Enter the size of the array: ");
scanf("%d", &size);
array = (int *)malloc(size * sizeof(int));
printf("Enter the elements of the array: ");
for (i = 0; i < size; i++)
{
scanf("%d", &array[i]);
}
printf("Enter the new size of the array: ");
scanf("%d", &new_size);
if (new_size > size)
{
array = (int *)realloc(array, new_size * sizeof(int));
for (i = size; i < new_size; i++)
{
array[i] = 0;
}
}
else if (new_size < size)
{
array = (int *)realloc(array, new_size * sizeof(int));
}
printf("The new array is: ");
for (i = 0; i < new_size; i++)
{
printf("%d ", array[i]);
}
free(array);
return 0;
}Dynamic Array Resizing — Free C Code Example
Demonstrates dynamic memory allocation and resizing of an array using malloc and realloc. This free code example is available in C and can be copied and run immediately — no account or signup required. Use the language tabs above to switch between implementations.
How to Use This Code
- Select your language — click the language tab (C, Java, C++, or Python) above the code viewer.
- Copy the code — use the copy button in the top-right corner of the code block.
- Run it — paste into a file with the correct extension (.c, .java, .cpp, .py), compile, and run using your terminal or IDE.
- Follow the on-screen instructions in the terminal to provide any required inputs.
Frequently Asked Questions
What does this program do?
Demonstrates dynamic memory allocation and resizing of an array using malloc and realloc.
Which languages is it available in?
Available in C. Switch between implementations using the tabs at the top of the code viewer.
How do I run this code?
Copy the code, save it with the right file extension (.c, .java, .cpp, or .py), then compile or run it with your installed compiler or interpreter (GCC, JDK, G++, Python 3).
Is this code free?
Yes — free to view, copy, and use. No account required.