此C代码应生成100万个随机数。在编译代码多次时,我使用srand()来辅助伪随机生成问题。我认为理论上这个代码应该可行,但它似乎错过了可能导致溢出的东西。任何想法为什么它在执行过程中停止工作?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
FILE *ofp;
int k=0, i=1000000;;
int array[i];
ofp=fopen("output.txt","w");
while (ofp==NULL)
{
printf("File is corrupted or does not exist, \nplease create or fix the file and press enter to proceed");
getchar();
}
srand(time(NULL));
rand();
for (k=0; k<1000000; k++)
{
array[k] = rand()%100;
fprintf(ofp, "%d\n", array[k]);
}
return 0;
}
答案 0 :(得分:0)
修改您的代码如下:
// ...
#define MAX 1000000
// ...
int main() {
int array[MAX]; // proper static allocation
// ...
if (ofp == NULL) { // while loop has no meaning in here
// ... }
// ...
return 0;
}
不要忘记关闭您已打开的流后,将已分配的资源释放回系统(在您的情况下,您的流程最终会被终止,所以如果你没关系没有打算关闭它)
编辑:根据C99规范,它允许使用某些类型来初始化静态分配的数组,但C89却没有。此外,为避免可能的堆栈溢出问题,请尝试通过调用 malloc 或 calloc 函数在代码中动态分配数组。例如:
// ...
#include <stdlib.h>
// ...
int main()
{
// ...
int* array = malloc(sizeof(int) * i);
// ...
free(array); // don't forget to free it after you're done.
return 0;
}