如果我想使用大型数组,比如 mpz_t A[100000],我在编译期间得到“分段错误(核心转储)”。有没有更简单的方法来解决这个问题?
GMP 中的大数组
计算科学
编程范式
2021-12-02 10:51:47
2个回答
tpg2114 的评论很到位。尝试:
/* at top */
#include <stdlib.h>
/* definition */
mpz_t *A;
/* initialization of A */
A = (mpz_t *) malloc(100000 * sizeof(mpz_t));
if (NULL == A) {
printf("ERROR: Out of memory\n");
return 1;
}
/* no longer need A */
free(A);
如果malloc
此处的调用触发错误,则您的系统中没有足够的可用内存。
如果您对在堆栈上使用静态数组感兴趣,那么您可以尝试使用ulimit
命令增加 Linux 中的堆栈限制大小。
您也可以考虑mpz_class
在 C++ 中使用 ( ref .) 而不是mpz_t
. 它可以使任意精度的算术变得简单。
这是一个随机的例子:
#include <gmp.h>
#include <gmpxx.h>
#include <iostream>
using namespace std;
int main() {
mpz_class A[100000];
for(int i=0;i<100000;i++) A[i]=142412+i;
for(int i=0;i<100000;i++) cout << i << " " << A[i] << endl;
return 0;
}
用例如编译:
g++ [[filename]] -lgmp -lgmpxx
其它你可能感兴趣的问题