Difference between static and dynamic arrays

A static array is an array that is created at compile-time. Because it is created at compile-time, you must define its size beforehand. Once a static array is created, its size is fixed and cannot be resized.

If an array of size seven is declared, you can only store up to seven elements in it. You can modify or delete elements by assigning them a null value (or an equivalent representation), but you cannot change the size of the array itself.

#include <stdio.h>
int main(int argc, char **argv) {
	const int SIZE = 7;
	int arr[SIZE] = {0}; // {0, 0, 0, 0, 0, 0, 0}

	arr[0] = 1;
	arr[6] = 7;

	printf("1st element: %d\n", arr[0]); // 1
	printf("7th element: %d\n", arr[6]); // 7

	arr[0] *= 10;
	arr[6] *= 10;

	printf("1st element: %d\n", arr[0]); // 10
	printf("7th element: %d\n", arr[6]); // 70

	arr[0] = '\0';
	
	printf("1st element: %d\n", arr[0]); // null
	return 0;
}

A dynamic array, on the other hand, is created at runtime. This means you can create an array without knowing its size in advance. Unlike static arrays, the size of a dynamic array is not fixed and can be resized at any time, as long as there is enough available memory.

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

int main(int argc, char **argv) {
	int size = 0;

	// get the array size from the user
	printf("enter the array size: ");
	scanf("%d", &size);

	// create an array by allocating memory to hold 'size' elements
	int *arr = (int *)malloc(sizeof(int) * size);

	arr[0]      = 1;
	arr[size-1] = size;

	printf("1st element: %d\n", arr[0]);
	printf("last element: %d\n", arr[size-1]);

	// re-scale the array by getting a new size
	printf("Re-enter the array size: ");
	scanf("%d", &size);

	// re-allocate
	arr = realloc(arr, sizeof(int) * size);

	arr[size-1] = size;

	printf("1st element: %d\n", arr[0]);
	printf("last element: %d\n", arr[size-1]);

	// deallocate array
	free(arr);

	return 0;
}

One important consideration when using dynamic arrays is that you must manually deallocate any allocated memory before the program exits to prevent memory leaks (250130081822).

Backlinks: