【发布时间】:2021-12-05 06:20:51
【问题描述】:
我是 C 编程新手,在开发本练习时遇到了无法解决的错误:
字段必须具有恒定大小:永远不会支持“结构中的可变长度数组”扩展
#include <stdio.h>
#include <stdlib.h>
int main(int argc, const char * argv[]) {
int nChapters = 2;
typedef struct {
char title[50];
char author[50];
} Heading;
typedef struct {
char title[50];
int number_pages;
} Chapter;
typedef struct {
Heading heading;
Chapter chapters[nChapters]; //Fields must have a constant size: 'variable length array in structure' extension will never be supported
} Book;
printf("\n");
system("read -p 'Press enter to continue...' ");
printf("Hello, World!\n");
return 0;
}
如果我用 chapters[2] 之类的 int 替换 chapters[nChapters],程序运行没有问题。提前致谢!
【问题讨论】:
-
错误信息确实说明了一切。
nChapters是一个变量,而不是编译时常量。结构中的数组只能使用编译时常量,例如实际的文字整数2。这是在 C 中使用宏的少数几个原因之一。就像在#define NCHAPTERS 2 -
你应该将
Chapter chapters声明为指针,然后动态分配内存 -
为什么它可以在其中一个在线编译器中工作? onlinegdb.com,我正在使用 Xcode
-
还要确保你没有编译为 C++。在 C++ 中,
const int被认为是一个整数常量表达式,但在 C 中不是。总体而言,C++ 在各种常量表达式和变量初始化形式方面更加灵活。
标签: c