Dynamic arrays are created at runtime
When declaring an array, you can create a static array if the size of the data is known beforehand (240611103553). However, in most real-world scenarios, especially when dealing with dynamic data, the exact size is unknown in advance.
With dynamic arrays, you don’t need to define the size beforehand. Instead, you can determine the required size at runtime—for example, by reading data from a file or accepting user input—and allocate enough memory accordingly. Unlike static arrays, dynamic arrays are resizable, allowing for more flexibility.
While dynamic arrays may seem like a better choice than static arrays (250130073757), they come with a crucial caveat: manual memory management. When you allocate memory dynamically, you must also explicitly deallocate it to prevent memory leaks (250130081822). If your program continuously allocates memory without freeing unused memory, it can lead to excessive memory consumption and degrade performance over time.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
// allocate memory to store 7 int-type elements
int *arr = (int *)malloc(sizeof(int) * 7);
arr[0] = 1;
arr[6] = 7;
// arr[0]: 1 arr[6]: 7
printf("arr[0]: %d arr[6]: %d\n", *arr, arr[6]);
// deallocate memory
free(arr);
// arr[0]: <trash vaule> arr[6]: <trash value>
printf("arr[0]: %d arr[6]: %d\n", *arr, arr[6]);
return 0;
}