user1529540
user1529540

Reputation:

Making a big 2d array in c++

I have the following code:

#include <bits/stdc++.h>
using namespace std;

const int MAX=25;
const int TMAX=1 << MAX - 1;
double D[TMAX][MAX];

int main(){}

If I compile it I get

champ@champ-S451LN:~/code$ g++   kike2.cpp 
/tmp/ccuK5NOq.o: In function `__static_initialization_and_destruction_0(int, int)':
kike2.cpp:(.text+0x717): relocation truncated to fit: R_X86_64_PC32 against `.bss'
kike2.cpp:(.text+0x72a): relocation truncated to fit: R_X86_64_PC32 against `.bss'
collect2: error: ld returned 1 exit status

If I make MAX=22 I do not get this error, I think the problem is that TMAX*MAX exceeds 2^32.

Having access to such big 2D arrays would be useful for me. Does anyone know how to make them?

Here is what I did in the end:

#include <bits/stdc++.h>
using namespace std;

double** D = new double*[TMAX];// this is the DP array (its big so we save it differently)

int main(){
    for(int i = 0; i < TMAX; ++i){// store the big array
        D[i] = new double[MAX];
    }
}

Upvotes: 0

Views: 139

Answers (2)

Jcppython
Jcppython

Reputation: 199

You must use it in heap, rather than stack.

double* D = (double*)malloc(sizeof(double) * TMAX * MAX);
// D[d1][d2] can be accessed *(D + d1 * TMAX + d2)

Upvotes: 0

Aganju
Aganju

Reputation: 6395

You cannot make them really large on the stack, as the stack is nearly always severly more limited than main meory.

Use malloc or new instead, to create the object on the heap; main memory will be the only limit, including use of swap files if you want to go on that limb.

Upvotes: 2

Related Questions