Deaclaration of 3D variables with C++
I am using Gurobi with C++. I have a linear program involving decision variables with two indices x[][] and others with 3 indices w[][][] and f[][][]
There is no problem when declaring variables like this
GRBVar x[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
x[i][j] = model.addVar(0.0, 1.0, c[i][j], GRB_CONTINUOUS);
}
}
GRBVar f[n][n][n];
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
for (v = 0; v < n; v++) {
if(i!=j && j!=v && i!=v)
f[i][j][v] = model.addVar(0.0, 1.0, 0.0, GRB_CONTINUOUS);
}
}
}
GRBVar w[n][n][n];
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
for (v = 0; v < n; v++) {
w[i][j][v] = model.addVar(0.0, 1.0, 0.0, GRB_CONTINUOUS);
}
}
}
But when running, there is an error of stack overflow! Is there any mean to overcome this issue?
The cost matrix c[][] has two dimensions each one of 40. With less than 40, Gurobi runs successfully, but beyond 40, I have this issue of stack overflow.

Hi Ali,
Your arrays are too large to fit on the stack. By using sizeof, we see that each GRBVar element requires 8 bytes of memory. With \( n=39 \), your three GRBVar arrays require \(8(n^2 + 2n^3)\) = 961,272 bytes, or ~0.96 megabytes (one 2D array and two 3D arrays). With \( n = 40\), these arrays require 1,036,800 bytes, or ~1.04 megabytes. This suggests that your stack size is 1 megabyte.
Instead, you could allocate these arrays on the heap. E.g., for a threedimensional array:
GRBVar ***x = new GRBVar**[n];
for (int i = 0; i < n; i++) {
x[i] = new GRBVar*[n];
for (int j = 0; j < n; j++) {
x[i][j] = new GRBVar[n];
}
}Be sure to free this memory once it's no longer needed.
Thanks,
Eli
Please sign in to leave a comment.
Comments
2 comments