🏗️🔥Advanced
Flexible Array Members in Structure
Dynamic struct arrays
Flexible array members (C99 feature) allow structures with variable-length arrays.
Program Code
flexible_array.c
C
1#include <stdio.h>2#include <stdlib.h>3#include <string.h>45struct FlexArray {6 int size;7 int data[]; // Flexible array member8};910struct FlexArray* createArray(int n) {11 struct FlexArray *arr = malloc(sizeof(struct FlexArray) + n * sizeof(int));12 arr->size = n;13 return arr;14}1516int main() {17 // Create array with 5 elements18 struct FlexArray *arr = createArray(5);19 20 // Fill with data21 for (int i = 0; i < arr->size; i++) {22 arr->data[i] = (i + 1) * 10;23 }24 25 printf("Flexible array with %d elements:\n", arr->size);26 for (int i = 0; i < arr->size; i++) {27 printf("data[%d] = %d\n", i, arr->data[i]);28 }29 30 printf("\nSize of struct (without array): %zu bytes\n", sizeof(struct FlexArray));31 printf("Actual allocated: %zu bytes\n", sizeof(struct FlexArray) + arr->size * sizeof(int));32 33 free(arr);34 35 return 0;36}Output
Flexible array with 5 elements:
data[0] = 10
data[1] = 20
data[2] = 30
data[3] = 40
data[4] = 50
Size of struct (without array): 4 bytes
Actual allocated: 24 bytes
Related Examples
Want to Learn More?
Explore our comprehensive tutorials for in-depth explanations of C programming concepts.
Browse Tutorials