Talking about-[flexible array]

1. What is a flexible array

In C99, the last element in the structure is allowed to be an array of unknown size, which is called a flexible array member

E.g:

typedef struct S
{
    
    
	int i;
	int arr[];//柔性数组成员
}S;

or

typedef struct S
{
    
    
	int i;
	int arr[0];//柔性数组成员
}S;

2. Features of flexible array:

• The flexible array member in the structure must be preceded by at least one other member
• The size of the structure returned by sizeof does not include the memory of the flexible array

#include<stdio.h>
typedef struct S
{
    
    
	int i;
	int arr[0];//柔性数组
}S;
int main()
{
    
    
	printf("%d\n", sizeof(S));
	return 0;
}

Insert picture description here
• The structure containing flexible array members uses malloc() function to dynamically allocate memory, and the allocated memory should be larger than the size of the structure to adapt to the expected size of the flexible array

3. The use of flexible arrays

• Code description

#include<stdio.h>
#include<stdlib.h>
typedef struct S
{
    
    
	int i;
	int arr[0];//柔性数组成员
}S;
int main()
{
    
    
	S* ps = (S*)malloc(sizeof(S) + 5 * sizeof(int));
	int i = 100;
	for (int i = 0; i < 5; i++)
	{
    
    
		ps->arr[i] = i;
	}
	S* ptr = realloc(ps, 44);
	if (ptr != NULL)
	{
    
    
		ps = ptr;
		for (int i = 5; i < 10; i++)
		{
    
    
			ps->arr[i] = i;
		}
		for (int i = 0; i < 10; i++)
		{
    
    
			printf("%d ", ps->arr[i]);
		}
	}
	free(ps);
	ps = NULL;
	return 0;
}

• Graphical description

Insert picture description here

• operation result

Insert picture description here

4. Non-flexible array

• Code description

#include<stdio.h>
#include<stdlib.h>
typedef struct S
{
    
    
	int i;
	int* arr;
}S;
int main()
{
    
    
	S* ps = (S*)malloc(sizeof(S));
	ps->arr = malloc(5 * sizeof(int));
	for (int i = 0; i < 5; i++)
	{
    
    
		ps->arr[i] = i;
	}
	//调整大小
	int* ptr = realloc(ps->arr, 40);
	if (ptr != NULL)
	{
    
    
		ps->arr = ptr;
		for (int i = 5; i < 10; i++)
		{
    
    
			ps->arr[i] = i;
		}
		for (int i = 0; i < 10; i++)
		{
    
    
			printf("%d ", ps->arr[i]);
		}
	}
	//释放内存
	free(ps->arr);
	ps->arr = NULL;
	free(ps);
	ps = NULL;
	return 0;
}

• Graphical description

Insert picture description here

• operation result

Insert picture description here

5. The benefits of using flexible arrays

For example, 3 and 4 above, it can be seen that using flexible arrays has the following advantages:

• 方便释放内存
• 有利于访问速度,连续的内存有益于提高访问速度,也有益于减少内存碎片

Guess you like

Origin blog.csdn.net/weixin_50886514/article/details/113859259