Error when using static array in C structure

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 ‘staticstatic long history[100];

      

I do not know why? Does this mean that I cannot use static internal structures?

+3
c


source to share


2 answers


Unlike C ++, where struct

(which are completely equivalent to classes in terms of their functionality) are allowed to have static members, C is struct

not.

C allows you to create static variables with file system and function. If it history

must be static, make it static in the function it is accessing, or in the file if more than one function calls it.



However, if you need to history

be static, yours struct

becomes functionally equivalent to a single one int

, because it static

means "one array common to all instances of mine struct

". Chances are good that you wanted a non-static array, i.e. Each struct

has its own history

":

struct N{
    int id;
    long history[100];
};

      

+2


source to share


In C, a struct member cannot be static

; you are confusing this with C ++ static

for classes (and therefore C ++ structs), where it means that the property / method is not intended to be unique to a specific instance of the class (object). Note that in C ++ this also means everything it meant in C (and more). See here for more details: The static keyword and its various uses in C ++

In C, the keyword static

simply indicates the storage class of the symbol - if executed locally (in a function), it means that this variable is global, but only visible to that function, and if applied to an actual global variable, it limits the scope of the file it is in was announced. For more information see here: What does "static" mean?



If you "want to preserve the value of an array between function calls," just don't write these functions into it; I suspect your problem is trying to design your program in an object-oriented way, even if you are using C.

+1


source to share







All Articles