2

I am 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[];.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user1472747
  • 529
  • 3
  • 10
  • 25

1 Answers1

4

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.

Theodoros Chatzigiannakis
  • 28,773
  • 8
  • 68
  • 104
  • "Calculating sizes" is missing the interesting point: In C, array types are types, and the size of part of the type. – Kerrek SB Feb 17 '13 at 20:46
  • Alright, I did this. Now I get a weird error: expected ':', ',', ';', '}' or '__attribute__' before '=' token ` int list_header_size = 200; int list_sequence_size = 2000; struct list{ char *header = (char*) malloc(sizeof(list_header_size)); char *sequence = (char*) malloc(sizeof(list_sequence_size)); struct list *next; }; ` – user1472747 Feb 17 '13 at 22:13
  • @user1472747 Please post your modified code so that we can see what's wrong. – Theodoros Chatzigiannakis Feb 17 '13 at 22:15
  • I'm trying... but I can't figure out how to format code in the comment. I'll post it in the main post. – user1472747 Feb 17 '13 at 22:15
  • oh, wow. You're not supposed to set fields in the struct, are you... I'm an idiot >. – user1472747 Feb 17 '13 at 22:18
  • @user1472747 Well, the problem is that you can't be using `malloc` to initialize struct members in the struct definition. Just declare the fields as `char*` and do the initialization when you actually create instances of that struct. – Theodoros Chatzigiannakis Feb 17 '13 at 22:18
  • @TheodorosChatzigiannakis It depends how the symbols `list_header_size` and `list_sequence_size` are declared. Unfortunately, one gets the same error even when they are declared as `const int list_header_size = 100;` (and similar für `list_sequence_size`) - although the compiler _could_ compute the `struct` size then. – rplantiko Oct 19 '15 at 19:09