Flexible array members in C99

C99 supports the structure containing flexible array members, and its basic form is as follows:

struct data {
    int a;
    unsigned long b[];
};

When in use, there are the following requirements:

1) Flexible array members need to be written in the form of contents[ ];

2) Due to the incomplete type of the flexible array member, the sizeof operation cannot be performed on the member;

3) Flexible array members can only appear in the last position of the structure;

Instructions:

1) Dynamically allocate space

#include <stdlib.h>

struct data {
	int a;
	unsigned long b[];
};

int main(void)
{
	int i = 0, num = 3;
	struct data *d = malloc(sizeof(struct data) + sizeof(unsigned long) * num);

	d->a = 1;
	for (i = 0; i < num; ++i) {
		d->b[i] = (i + 2);
	}

	return 0;
}

2) Static assignment

#include <stdio.h>

struct data {
	int a;
	unsigned long b[];
};

struct data d = {1, {[1] = 2021}};

int main(void)
{
	printf("d.b[1]: %ld\n", d.b[1]);

	return 0;
}

The following usage is wrong, because the data assigned to the flexible array members is not static:

#include <stdio.h>

struct data {
	int a;
	unsigned long b[];
};

int main(void)
{
	struct data d = {1, {[1] = 2021}};
	printf("d.b[1]: %ld\n", d.b[1]);

	return 0;
}

The following error will be reported during compilation:

$ gcc -o main ./main.c
./main.c: In function 'main':
./main.c:10:9: error: non-static initialization of a flexible array member
  struct data d = {1, {[1] = 2021}};
         ^
./main.c:10:9: error: (near initialization for 'd')

 

Guess you like

Origin blog.csdn.net/choumin/article/details/114647018