3

I want to use a static array inside the following structure:

struct N{
    int id;
    static long history[100];
};
struct N Node[R][C];  // R is # of rows, C is # of coloumns

But I got this error:

P.c:38:2: error: expected specifier-qualifier-list before ‘static’
                 static long history[100];

I don't know why? Does it mean I cannot use static inside structures?

Mike
  • 380
  • 4
  • 19

2 Answers2

2

Unlike C++ where structs (which are fully equivalent to classes in terms of their functionality) are allowed to have static members, C structs are not allowed to do so.

C allows you to have file-scoped and function-scoped static variables. If history needs to be static, make it static in a function where it is accessed, or in a file if it's accessed by more than one function.

However, if you do need history to be static, your struct becomes functionally equivalent to a single int, because static means "one array shared among all instances of my struct". Good chances are that you needed the array to be non-static, i.e. "each struct has its own history":

struct N{
    int id;
    long history[100];
};
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

In C, a struct member cannot be static; you're confusing this with the C++ static for classes (and consequently C++ structs), where it means that a property/method is not intended to be unique to a particular instance of the class (object). Note that in C++ it also means everything it meant in C (and more) - see here for details: The static keyword and its various uses in C++

In C, the static keyword merely specifies the storage class of a symbol - if done locally (in a function), it means roughly that the variable is a global but only visible to that function, and if applied to an actual global variable it restricts its scope to the file where it's declared. For more info, see here: What does "static" mean?

If you "want to keep the value of the array between function invocations", then simply don't write to it in these functions; I suspect your problem is trying to design your program in an object-oriented manner, even though you're using C.

Community
  • 1
  • 1
user4520
  • 3,401
  • 1
  • 27
  • 50
  • In fact you are right, I want to "simulate" OO manner as C structure since I understand Java well. Thank you for your reply. – Mike Nov 17 '15 at 15:48