Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring variable sized array without using dynamic memory allocation

Tags:

c++

scope

dynamic

I want to allocate variable sized 2D array in a function without using new operator such that this 2D array is available to other functions in the same file.

    void draw(int i)
    {   size=i;   }

    void assign(char symbol)
    {
        char one[size][size];
        /// ... Assigning values to one  ...
    }
    void display()
    {   /// Displaying values of one[size][size]
        for(int i=0;i<size;i++)
        {
            for(int j=0;j<size;j++)
            cout<<one[i][j];
            cout<<endl;
        }
    }

Execution order of functions is draw -> assign -> display

This question may have been asked earlier. But my problem is.. -> I can't declare the array outside assign function globally because value of size is not known. -> I can't use "one" array in "display" function because its scope is limited to "assign" function.

And I also don't want to use either new or malloc operators. Please help if there is any alternative available.

like image 834
Jekin Avatar asked Oct 14 '25 18:10

Jekin


2 Answers

C++ doesn't support stack-allocated Variable Length Arrays like for example C99. You should use std::vector<T> instead. If you really want to use stack allocation you can use alloca().

like image 171
mauve Avatar answered Oct 18 '25 12:10

mauve


There is no way to do this. The array "one" is a temporary on the stack in the assign function. It gets destroyed whenever you leave the assign function.

So you need to allocate memory somehow.

If you only ever use one copy of the "one" array at a time, you could declare it in global scope with space large enough for a comfortable upper bound. And check each time that you use it that the static global array is large enough.

Is your concern performance? Or are you on a platform where memory allocation is not possible?

Some other options: statically allocate the array outside the system, and pass it in as an argument to each function.

Or if all the functions can be called from a single higher level "owner" function, you could allocate the array dynamically on the stack with "alloca".

E.g.

system()
{
   char one = alloca( size );
   draw( one, ... );
   assign( one, ...);
   display( one, ... );
}
like image 43
Rafael Baptista Avatar answered Oct 18 '25 11:10

Rafael Baptista



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!