我的结构如下:
struct Query {
int pages[];
int currentpage;
};
Run Code Online (Sandbox Code Playgroud)
我想知道在创建结构后是否可以设置此数组的大小.
Query new = malloc(sizeof(struct Query));
Run Code Online (Sandbox Code Playgroud)
在此之后,我将执行一些计算,然后告诉我pages[]需要的大小.如果pages[]需要大小为4,我该如何设置它?
Dav*_*eri 14
在C99中,您可以使用Flexible数组成员:
struct Query {
int currentpage;
int pages[]; /* Must be the last member */
};
struct Query *new = malloc(sizeof(struct Query) + sizeof(int) * 4);
Run Code Online (Sandbox Code Playgroud)
将pages成员类型更改为指针.
struct Query {
int *pages;
int currentpage;
};
struct Query *test = malloc(sizeof(struct Query));
if (test != NULL)
{
//your calculations
test->pages = malloc(result_of_your_calcs);
if (test->pages != NULL)
{
// YOUR STUFF
}
else
{
// ERROR
}
}
else
{
// ERROR
}
Run Code Online (Sandbox Code Playgroud)
如果你free的结构是你的结构,那么你必须这样做.
free(test->pages);
free(test);
Run Code Online (Sandbox Code Playgroud)
您可以使用Flexible数组成员(@ AlterMann的答案中的详细信息)(C99 +)或零长度数组(GNU C).
引自https://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html,
在GNU C中允许零长度数组.它们作为结构的最后一个元素非常有用,它实际上是一个可变长度对象的头:
Run Code Online (Sandbox Code Playgroud)struct line { int length; char contents[0]; }; struct line *thisline = (struct line *) malloc (sizeof (struct line) + this_length); thisline->length = this_length;
对于标准C90,链接网站提及
在ISO C90中,您必须给出
contents1的长度,这意味着您要浪费空间或使参数复杂化malloc.
这意味着对于代码在标准C90/C89中工作,char contents[0];应该是char contents[1];.