Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
844 views
in Technique[技术] by (71.8m points)

c - Variably modified 'variable_name' at file scope error?

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

Code:

struct list{
  char header[list_header_size];
  char sequence[list_sequence_size];
  struct list *next;
};

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[];

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...