Array for loop, C99

I asked the previous question about declaring an array in a for loop, for example.

for(i=0;i<=1000;i++){
    float arrayone[(length[i])];
    do a bunch of other stuff
}

Basically, I'm trying to make an array whose length may vary depending on what stage the program is at. I do not want the data of the array to be persistent (for example, arrayone [] []), because it is large and there are many steps.

Therefore, I was told that it is legal to declare an array only in this area, like this. But will it try to store 1000 copies of the array by the end, which I don't want? I'm a beginner, so I don’t understand the nuances of what blocks really do.

An alternative for me is simply to create an array outside the loop that has the maximum length ever needed, and overwrite it at every step.

Edit: use for array: I have a global array. Arrays in the loop are populated with the results of the function using this global array to save computation. Arrays are processed, ..., ... and finally are used to modify the global array. Then they are no longer needed.

+3
source share
2 answers

But will it try to store 1000 copies of the array by the end, which I don't want?

No, a new array will be allocated at the beginning of each iteration, and since the array is outside the scope at the end of the iteration, it will be freed at that time, so only one array exists at a time.

( ). , (, ), .

+7

, , , . , .

, , , , , .

( ), :

    for(i=0;i<=1000;i++){
      float * arrayone = (float*)malloc(i * sizeof(float));
    }

. - , , , . , 1000 . free , , , , , .

0

All Articles