My cpp project has static 2d array in a header file but it causing chkstk error. I want to make it dynamic. Is it really possible to do with in the header as making changes to all parts of the project ( about 12000 lines code ) is difficult.
Asked
Active
Viewed 1,351 times
0
-
Create a class with singleton pattern providing you with the array instance. – Stan Dec 16 '12 at 10:20
1 Answers
0
According to Dietmar's answer on a similar problem, most probably you need to put your static 2d array into a function so that it gets initialized in time.
Like this:
double**& my_array()
{
static double** local = NULL;
if(!local)
{
// init your array here
}
return local;
}
and you need to refer to your array like my_array()
instead of my_array
in the code.
EDIT:
For icepack's question: yeah, it looks rather strange (in my mind, a multi-array should be wrapped into a class anyway and then this would not happen). The reason for using this strange return type is the following:
// if you returned double** instead of double**&
my_array() = other_array; // would overwrite a temporary pointer
my_array(); // would be still the old array
If you use C++11, the cleanest solution is:
typedef std::array<std::array<double, second_dim>, first_dim> my_array_t;
my_array_t& my_array()
{
static my_array_t local = initial_value();
return local;
}
and you use my_array
the same as before, with my_array()
.
Even if you don't use C++11, I suggest you define your own 2d_array class, it has no overhead over C arrays anyway, when you write it properly.

Community
- 1
- 1

Barney Szabolcs
- 11,846
- 12
- 66
- 91
-
1`double**&` ? WTF? Such code shouldn't be created by any decent programmer. – SomeWittyUsername Dec 16 '12 at 07:55
-
1@icepack: I agree it is rather strange, see my explanation in the updated answer. – Barney Szabolcs Dec 16 '12 at 08:02