logo

How to use dynamically allocated arrays

#include <stdio.h> #include <stdlib.h> #include <string.h> int* arr; size_t arrSize = 256; // 1) Do you need an array used in many other places? // 2) Do you know the max amount of elements? // 3) Is that max amount too big? int main(int argc, char* argv[]) { arr = calloc(256, sizeof(int)); if (arr == NULL) { fprintf(stderr, "Array not allocated!\n"); return 1; } arr[10] = 17; printf("%d\n", arr[10]); arrSize *= 2; arr = realloc(arr, arrSize * sizeof(int)); if (arr == NULL) { fprintf(stderr, "Array not reallocated!\n"); return 1; } printf("%d\n", arr[10]); free(arr); return 0; }
Course thumb

The C programming language made simple

Courses with this lesson