【问题标题】:Making a big 2d array in c++在 C++ 中制作一个大的二维数组
【发布时间】:2017-05-09 02:46:25
【问题描述】:

我有以下代码:

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

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

int main(){}

如果我编译它,我会得到

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

如果我设置 MAX=22,我没有收到此错误,我认为问题在于 TMAX*MAX 超过 2^32。

访问如此大的二维数组对我很有用。有人知道怎么做吗?

这是我最后所做的:

#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];
    }
}

【问题讨论】:

  • 在我的 ubuntu 15.10 上,pthread_attr_getstacksize() 将线程的堆栈大小报告为 8 MBytes。

标签: c++ arrays memory


【解决方案1】:

你不能让它们在堆栈上变得非常大,因为堆栈几乎总是比主内存更受限制。

使用mallocnew 在堆上创建对象;主内存将是唯一的限制,如果您想继续使用交换文件,则包括使用交换文件。

【讨论】:

  • 非常感谢。我想我明白了,但是您能否添加一行代码,说明您将如何明确地做到这一点?
  • 你推荐什么 new 或 malloc?
  • here(你确实意识到这会要求系统同时提供超过 3 GB 的 RAM,对吧?)
  • D 是全局变量,不在堆栈中。
  • @1201ProgramAlarm 是的 - 我猜这个错误表明它实际上对于 BSS 段来说太大了,但是 Aganju 的解决方案应该仍然有效。是的,Jorge,我的数学可能已经关闭,或者您的计算机可能擅长使用交换空间,无论哪种方式都很高兴它起作用了!
【解决方案2】:

您必须在堆中使用它,而不是在堆栈中。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-29
    • 1970-01-01
    相关资源
    最近更新 更多