使用大整数数组

如何使用大整数,我需要GMP库吗?
我想要一个元素,其元素从0到2 ^ 32开始
如何让这个工作:

#include  int main(){ unsigned int i,j=0,sz=4294967295; unsigned int A[sz]; A[j]=0; for(i=1;i<=sz;i++){ A[i]=A[j]+1 ; j++; printf("%u\n",A[i]); } return 0; } 

错误:进程退出,返回值为3221225725
数组是太大还是什么?

据谷歌称,你的Aarrays约为17千兆字节 。 好多啊。 你可能已经溢出了堆栈。

如果你真的需要这么多的内存,你可以使用malloc()代替它,但是在较旧的 32位架构中,你基本上没有运气(地址空间有4 GB的硬上限,减去内核空间) 。

您正在分配一个16-17GB的数组,它溢出堆栈。 正如haccks所说,你可以尝试在堆上进行分配。

 unsigned int *A = malloc(sizeof(int)*sz); if(A == NULL) { printf("Unable to allocate memory for array.\n"); exit(1); } 

不要忘记随后自由:

  ... free(A); return 0; } 

而且你的代码中也有一个错误。 数组的索引从0size - 1 。 当i成为sz写入无效内存时。

 for(i=1;i<=sz;i++) { // Will cause invalid memory write A[i]=A[j]+1 ; j++; printf("%u\n",A[i]); } 

改成:

 for(i=1; i < sz; i++) { A[i] = A[j] + 1; j++; printf("%u\n", A[i]); } 

数组的内存在堆栈上分配,其大小通常很小,会导致堆栈溢出。 您需要在堆上为这么大的数组分配内存。 两个地方

 unsigned int A[429496729]; 

main或使用动态内存分配

 unsigned int *A = malloc(sizeof(int)*sz); if(A == NULL) exit(0); 

完成free(A)使用free(A)释放分配的内存。

更好地使用来自limits.h定义常量,例如UINT_MAX或ULONG_MAX,并检查用于索引数组的类型(也许你的unsigned int转换为int)