Table of Contents

C VLA

C VLA (Variable Length Arrays) (C99) lets you declare arrays with size determined at runtime: int arr[n] where n is computed. VLAs are stack-allocated; use for temporary arrays when size isn't known at compile time. Avoid large VLAs (stack overflow risk); use malloc for large/long-lived arrays.

Use VLAs for small temporary arrays; use malloc for large or persistent data.

Example

// compile: gcc -std=c99 -o vla vla.c
// run: ./vla
// description: variable-length arrays
 
#include <stdio.h>
 
void process_array(int n) {
    // VLA: size determined at runtime
    int arr[n];
 
    // Initialize
    for (int i = 0; i < n; i++) {
        arr[i] = i * 2;
    }
 
    // Use
    printf("Array of size %d: ", n);
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}
 
// VLA in function parameter (C99)
void print_matrix(int rows, int cols, int matrix[rows][cols]) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("%d ", matrix[i][j]);
        }
        printf("\n");
    }
}
 
int main() {
    int size;
    printf("Enter array size: ");
    scanf("%d", &size);
 
    process_array(size);
 
    // 2D VLA
    int matrix[3][4] = {
        {1, 2, 3, 4},
        {5, 6, 7, 8},
        {9, 10, 11, 12}
    };
 
    print_matrix(3, 4, matrix);
 
    return 0;
}

Common patterns

Basic VLA:

Multi-dimensional VLA:

Function parameters:

Stack overflow risk:

Performance:

Limitations:

Alternatives: