在 C 中定义弹性/柔性结构 [英] Defining elastic/flexible structure in C

查看:29
本文介绍了在 C 中定义弹性/柔性结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个任务要做,任务内容是:

I have a task to do and the content of the task is:

请提出链表的定义,以灵活的结构保持人的姓名和年龄.然后编写插入具有给定名称和年龄的元素的过程.

Please suggest a definition of linked list, which will keep the person's name and age in a flexible structure. Then write the procedure for inserting elements with the given name and age.

究竟什么是柔性结构?如何定义?然后怎么分配大小?

What exactly is a flexible structure? How to define it? And then how to malloc the size?

typedef struct Test {
int age; // ?
char name[?]; // ?
struct Test * next;
}Structure;

int main(void) {
Structure *one = malloc(???);
}

推荐答案

您走对了.但是,没有灵活的结构".您想在 struct 中使用灵活数组成员(自 C99 起可用):

You are on the right track. However, there is no "flexible structure". You want to use a flexible array member (avail since C99) in a struct:

typedef struct {
    int age;
    size_t name_size;    // size of the array, not length of the name!
    char name[];         // Flexible array member
} Structure;

int main(void) {
    Structure *one = malloc(sizeof(*one) + SIZE_OF_NAME_ARRAY);
}

注意我添加了一个 name_size 字段.C 不存储分配数组的大小,因此您可能需要它来进行安全复制/比较等(防止缓冲区溢出).

Note I added a name_size field. C does not store the size of allocated arrays, so you might need this for safe copy/compare, etc. (prevent buffer overflows).

使用 *one 使该术语独立于实际使用的类型.这种结构的大小就好像数组有零个元素一样.但是,它将正确对齐,因此它可以与没有数组的相同 struct 不同.

Using *one makes this term independent of the actual type used. The size of such a struct is as if the arrray had zero elements. However, it will be properly aligned, so it can differ from the same struct without the array.

另请注意,如果您使用的不是 char 数组,则必须将分配的大小更改为类似 sizeof(element_type) * ARRAY_SIZE 的内容.这对于 char 不是必需的,因为它们的大小由标准定义为 1.

Also note that you have to change the allocated size if you use other than a char array to something like sizeof(element_type) * ARRAY_SIZE. This is not necessary for chars, as their size is defined by the standard to be 1.

这篇关于在 C 中定义弹性/柔性结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆