问题描述
C 新手.编译时出现以下错误:
New to C. I'm getting the following error when compiling:
error: variably modified 'header' at file scope
error: variably modified 'sequence' at file scope
代码:
struct list{
char header[list_header_size];
char sequence[list_sequence_size];
struct list *next;
};
我认为这个错误意味着编译器需要从一开始就知道这些变量是什么.因此,我将调用结构体的 main() 移动到程序的末尾.我也尝试在程序开始时声明变量,但我不确定我是否正确这样做.我试过 char header;
和 char header[];
I thought the error meant that the compiler needed to know what these variables were from the beginning. So, I moved main(), which is where the struct is called, to the end of the program. I also tried declaring the variables at beginning of the program, but I'm not sure if I did that correctly. I tried char header;
and char header[];
推荐答案
你说得对,编译器需要知道结构体成员的类型.它需要知道类型的原因之一是它可以计算大小.但是,在您的情况下,它无法知道大小,因为在您的结构中您定义了两个不是恒定大小的数组.因此,编译器不知道结构体的总大小,这违背了了解类型的目的.
You are right that the compiler needs to know the types of the members of the struct. One reason why it needs to know the types is so that it can calculate sizes. In your case, however, it can't know the sizes because in your struct you have defined two arrays that are not of a constant size. Therefore, the compiler doesn't know the total size of the struct and this defeats the purpose of knowing the types.
最接近你想要的是用两个 char
指针替换两个 char
数组并分配它们将动态指向的内存.
The closest to what you want is to replace the two char
arrays with two char
pointers and allocate the memory they will point to dynamically.
这篇关于在文件范围错误时可变修改“variable_name"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!