gpt4 book ai didi

c - 随机数生成代码不起作用[可能是堆栈溢出]

转载 作者:行者123 更新时间:2023-11-30 20:38:16 25 4
gpt4 key购买 nike

此 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;
}

最佳答案

按以下方式修复您的代码:

// ...
#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 不允许。此外,为了避免可能的堆栈溢出问题,请尝试通过调用 ma​​lloccalloc 函数在代码中动态分配数组。例如:

 // ...
#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;
}

关于c - 随机数生成代码不起作用[可能是堆栈溢出],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29812215/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com