我们可以有一个可变长度数组类型的结构元素吗? [英] Can we have a struct element of type Variable length array?

查看:23
本文介绍了我们可以有一个可变长度数组类型的结构元素吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以声明一个可变长度的结构元素吗?

Can we declare a structure element of variable length?

条件如下:

typedef struct
{
   uint8_t No_Of_Employees;
   uint8_t Employee_Names[No_Of_Employees][15];
}st_employees;

推荐答案

如果在 C99 中编码或 C11,您可能想要使用 灵活数组成员(您没有给出明确的维度,但你应该在头脑中在运行时有一个关于它的约定).

If coding in C99 or C11, you might want to use flexible array members (you don't give an explicit dimension, but you should have a convention about it at runtime in your head).

 typedef struct {
    unsigned No_Of_Employees;
    char* Employee_Names[]; // conventionally with No_of_Employees slots
 }st_employees;

对于任何数组,灵活数组成员的每个插槽都有固定的大小.我正在使用指针(例如,我的 Linux/x86-64 机器上的 8 个字节).

As for any array, each slot of a flexible array member has a fixed size. I'm using a pointer (e.g. 8 bytes on my Linux/x86-64 machine).

(在 C99 标准之前的旧编译器中,您可能会尝试给出一个 0 维度,例如 char* Employee_Names[0];,即使它违反标准)

(In old compilers before the C99 standards, you might try give a 0 dimension like char* Employee_Names[0]; even if it is against the standard)

然后您将使用例如分配这样的结构

Then you would allocate such a structure using e.g.

 st_employees* make_employees(unsigned n) {
    st_employees* s = malloc(sizeof(s_employees)+n*sizeof(char*));
    if (!s) { perror("malloc make_employees"); exit(EXIT_FAILURE); };
    s->No_of_Employees = n;
    for (unsigned i=0; i<n; i++) s->Employe_Names[i] = NULL;
    return s;
 }

你可能会使用 (with strdup(3)在堆中复制一个字符串)就像

and you might use (with strdup(3) duplicating a string in the heap) it like

 st_employees* p = make_employees(3);
 p->Employee_Names[0] = strdup("John");
 p->Employee_Names[1] = strdup("Elizabeth");
 p->Employee_Names[2] = strdup("Brian Kernighan");

您需要一个 void destroy_employee(st_employee*e) 函数(留给读者作为练习).它可能应该循环 ifree 每个 e->Employee_Names[i],然后 free(e);...

You'll need a void destroy_employee(st_employee*e) function (left as an exercise to the reader). It probably should loop on i to free every e->Employee_Names[i], then free(e);...

不要忘记记录有关内存使用的约定(谁负责调用 mallocfree).阅读有关 C 动态内存分配的更多信息(并且害怕 内存碎片缓冲区溢出 和任何其他未定义行为).

Don't forget to document the conventions about memory usage (who is in charge of calling malloc and free). Read more about C dynamic memory allocation (and be scared of memory fragmentation and buffer overflows and any other undefined behavior).

如果使用 GCC 早于 GCC 5 一定要使用 gcc -std=c99 -Wall 编译,因为旧的 GCC 4 编译器的默认标准是 C89.对于较新的编译器,请询问所有警告以及更多警告,例如gcc -Wall -Wextra...

If using a GCC older than GCC 5 be sure to compile with gcc -std=c99 -Wall since the default standard for old GCC 4 compilers is C89. For newer compilers, ask for all warnings and more of them, e.g. gcc -Wall -Wextra...

这篇关于我们可以有一个可变长度数组类型的结构元素吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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