C language - flexible array

C language - flexible array

Flexible Array (Flexible Array) is a feature in C language, which allows the size of the last member of the array to be 0 or unknown, does not give a specific length when defining the array, and dynamically allocates the required memory space at runtime .

Using flexible arrays can efficiently handle variable-length data structures, such as storing variable-length data in a structure.

Here's an example using flexible arrays:

#include <stdio.h>
#include <stdlib.h>

struct MyStruct {
    
    
    int size;
    int data[];
};

int main() {
    
    
    int n = 5;
    struct MyStruct* myStruct = malloc(sizeof(struct MyStruct) + n * sizeof(int));
    myStruct->size = n;

    for (int i = 0; i < n; i++) {
    
    
        myStruct->data[i] = i;
    }

    printf("Size: %d\n", myStruct->size);
    for (int i = 0; i < myStruct->size; i++) {
    
    
        printf("Data[%d]: %d\n", i, myStruct->data[i]);
    }

    free(myStruct);
    return 0;
}

In the above example, a flexible array data[] is defined in the MyStruct structure, which represents variable-length data. At runtime, allocate the required memory space as needed, and use the malloc function for dynamic memory allocation.

Through flexible arrays, we can conveniently store data of different lengths according to needs, and only need to dynamically specify the length of the array when allocating memory, making the data structure more flexible and efficient. It should be noted that after use, the free function must be used to release the dynamically allocated memory space to prevent memory leaks.

Guess you like

Origin blog.csdn.net/m0_58235748/article/details/131939639