Detailed explanation of flexible arrays

Preface: Flexible array is a newly added concept in C99. It is the last member of the structure. Because its size is unknown, it is very flexible and is called soft.

1 Does the flexible array occupy the space of the structure?

   not taking

typedef struct Stu
{
	char y;
	int x;
	int arr[];//有些编译器不支持这样写,可以写成int arr[0],这个就是柔性数组
}St;
int main()
{
	//这里我们可以计算一下柔性数组到底计不计算空间
	printf("%d", sizeof(St));//这里涉及结构体的位段后面再说
	return 0;
}

We see that the size of the structure is 8, so the flexible array does not take up space.

2 How to use flexible arrays

Using dynamic memory allocation, let’s design a program based on yesterday’s dynamic memory management.

typedef struct Stu
{
	char y;
	int x;
	int arr[];//有些编译器不支持这样写,可以写成int arr[0],这个就是柔性数组
}St;
int main()
{
	//这里我们可以计算一下柔性数组到底计不计算空间
	printf("%d\n", sizeof(St));//这里涉及结构体的位段后面再说
	St s = { 0 };
	St* p = NULL;
	p = &s;
	p = (St*)malloc(sizeof(int) * 10+sizeof(St));
	if (p == NULL)
		return 0;
	for (int i = 0; i < 10; i++)
	{
		p->arr[i] = i;
		printf("%d ", p->arr[i]);
	}
	//如果后面要多开辟空间的话
	p = (St*)realloc(p,sizeof(int) * 15 + sizeof(St));
	for (int i = 10; i < 15; i++)
	{
		p->arr[i] = i;
		printf("%d ", p->arr[i]);
	}
	free(p);
	p = NULL;
	return 0;
}

3 A simulated implementation of flexible arrays (with flaws, but in general flexible arrays are easy to use)

Because the flexible array only needs to release the heap area memory once, and the flexible array does not occupy the structure memory

typedef struct Stu
{
	char y;
	int x;
	int* arr;
}St;

int main()
{
	printf("%d\n", sizeof(St));//指针占用内存空间
	//先给结构体开辟空间
	St* p = (St*)malloc(sizeof(St));
	//然后指针指向的空间开辟
	p->arr = (int*)malloc(sizeof(int) * 10);
	//判断是否为空
	if (p == NULL || p->arr == NULL)
		return 1;
	//不为空继续下面的程序
	p->x = 1;
	p->y = 'w';
	for (int i = 0; i < 10; i++)
	{
		p->arr[i] = i;
		printf("%d ", p->arr[i]);
	}
	//用完后记得释放内存,先释放小的,再释放大的
	//如果你先释放大的话,那么指针arr没有了,怎么找arr指向的那块空间呢?
	free(p->arr);
	free(p);
	//然后置空
	p->arr = NULL;
	p = NULL;
	return 0;
}

Guess you like

Origin blog.csdn.net/2301_79811170/article/details/134853549