c-vla
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:
type name[runtime_value]- Size determined at runtime
- Stack-allocated (automatic storage)
Multi-dimensional VLA:
int matrix[rows][cols]- Useful for temporary matrices
- All dimensions can be runtime-determined
Function parameters:
void func(int n, int arr[n])(C99)- Size parameter can precede array
- Allows dimension-aware functions
Stack overflow risk:
- VLAs on stack, not heap
- Large VLAs can overflow stack
- Portable code should limit size
- Embedded systems risk: very limited stack
Performance:
- No allocation overhead (like stack variables)
- Bounds not checked (like static arrays)
- Fast access (stack-local)
Limitations:
- C99/C11, not C89
- Some compilers don't support
- Size can't be negative (undefined behavior)
- Can't be static or extern
Alternatives:
- malloc/free for large arrays
- Compile-time fixed sizes
- dynamically allocated arrays (alloca)
c-vla.md · Last modified: by 127.0.0.1
