Array in for loop, C99

I asked a previous question about declaring an array in a for loop, e.g.

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

Basically, I'm trying to do an array whose length can be varied based on what step the program is on. I don't want to keep the array data saved permanently (like arrayone[][]), since it's big and there's lots of steps.

So I was told it's legal to declare the array only within this scope 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 the blocks really do.

The alternative for me is just to make an array outside of the loop which has the maximum length ever needed, and to overwrite that at every step.

Edit: The use for the array is: I have a global array. The arrays in the loop are filled with function results using that global array, to save computing. The arrays get manipulated,...,...,and finally are used to change the global array. Then they're not needed anymore.

Answers


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

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

That is the point of automatic variables (which that array is). At the end of the scope in which they are declared (usually but not always delimited by braces) they are automatically deallocated.


After each iteration of your loop is done all the variables that were declared inside your loop will be destroyed, including your array. So only one copy of your array will be kept.

That being said, however, you should know that initializing the array outside your loop is probably better, because you won't have to allocate memory on the stack every iteration.

If you were dynamically allocating your array (which you're not in your example) like this:

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

then you have a problem. Here the local variable is the pointer, which when it gets destroyed you can no longer access the memory you allocated. This is the case where you would end up with 1000 different arrays in memory at once. You could free your memory before the pointer is destroyed, but I maintain that having the array declared outside the loop is still better.


Need Your Help

Android Development Machine

android

With the latest SDK release, and the ability to download separate platforms releases into the SDK, the hardware resources required to develop for Android have increased significantly. Assuming that...