我们可以有一个可变长度数组类型的struct元素吗? [英] Can we have a struct element of type Variable length array?
问题描述
我们可以声明一个可变长度的结构元素吗?
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)
然后,您将使用例如
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;
}
,您可能会使用(与 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)
函数(作为练习供读者阅读).它可能应该在每个e->Employee_Names[i]
上依次在i
上循环到free
,然后在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);
...
请不要忘记记录有关内存使用的约定(谁负责调用malloc
和free
).阅读有关 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 早于
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
...
这篇关于我们可以有一个可变长度数组类型的struct元素吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!