简体   繁体   中英

How to initialize a static C array?

Say I want to do something like this to increment a int array every time I call f():

void f()
{
  static int v[100]={1,2,3...100};
  for (int i=0; i<100; i++) v[i]++;
}

ie I want:

first call f(): v[100]={1,2,3...100};
second call f(): v[100]={2,3,4...101};
...

apparently the following will not do it:

void f()
{
  static int v[100]; for (int i=0; i<100; i++) v[i]=i+1;
  for (int i=0; i<100; i++) v[i]++;
}

Not sure how to achieve it. Thanks!

The static array declared inside the function can only be referenced inside it, and it exists as long as the program runs. It can be initialized as you hint in your first version.

The second version first fills the array with values and then increments them, each time the function is called. Presumably not what you want.

Either split the initializing and incrementing into two functions, defining the static array outside both, or just fill the array in by hand like your first version (could even write a program to generate the part initializing the array into a file, and then copy that into your source). The filling in of the array in this case is done by the compiler, there is no runtime penalty.

you may do this with another static variable which holds the mark or starting point for your array. say

{
    static int fst = 0,
        v[MAXSIZE] = {0};    //#define MAXSIZE 100
        fst++;
        for(int i = 0; i < (MAXSIZE+fst-1); i++) v[i] = i + fst;
}

You can't initialize your static array like that. That first for loop in your second code block will just get called every time f is called.

You could initialize the static v variable to NULL instead, and then before the for loop that actually increments the array elements, check for NULL and initialize with i+1 if necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM