简体   繁体   English

C程序在创建数组并写入.txt文件时会花费很多时间

[英]C program taking forever when creating array and writing to .txt file

I'm trying to create a random array of integers from 0-31 for a 256 x 256 array. 我正在尝试为256 x 256数组创建一个从0到31的整数随机数组。 The code works as I can do it for smaller arrays really well. 该代码可以正常工作,因为我可以很好地处理较小的数组。 However, when trying to create the 256x256 array and write it out to a .txt file it is taking forever to run. 但是,当尝试创建256x256数组并将其写出到.txt文件时,它将花费很多时间。 I'm new to C so any advice on how to fix this would be appreciated. 我是C的新手,所以对于如何解决此问题的任何建议将不胜感激。 thank you 谢谢

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

#define MaxC 256
#define MaxL 256

 int main(){

 FILE *fp;
 fp = fopen("arrays256.txt","w+");
     int c[257] = {0};
     int i=0,j=0,r;
     int n[MaxC][MaxL] = {{0}};

     //int* n = (int*)malloc(MaxC * MaxL * sizeof(int));
     srand(time(NULL));

     for(i = 0; i < MaxC; i++) {

       for(j = 0; j < MaxL; j++) {

         do {
            r=(rand()%32);
         } while( c[r] > 258);
         ++c[r];
         n[i][j]=r;
         printf("%3d",n[i][j]);
         fprintf(fp,"%3d",n[i][j]);
       }

       printf("\n");
       fprintf(fp,"\n");

     }
     //free(n);
     fclose(fp);
     return 0;

 }

Consider the effects of: 考虑以下影响:

do {
    r=(rand()%32);
} while( c[r] > 258);
++c[r];

This code is executed MaxC*MaxL times, due to the loops on i and j , which is 256•256 = 65,536 times. 由于ij上的循环,该代码被执行MaxC*MaxL次,即256•256 = 65,536次。 Each time, some r in the range 0 to 31 is chosen. 每次都选择0到31范围内的r The while loop excludes an r from being chosen if c[r] exceeds 258. This causes various c[r] to be incremented, with r ranging from 0 to 31. while循环排除一个r如果从被选择c[r]超过258这将导致各种c[r]被增加,与r范围从0到31。

Consider what happens when the loop has been executed 259•32 = 8,288 times. 考虑当循环执行259•32 = 8,288次后会发生什么。 Then each of the 32 c[r] must have been incremented to 259. At that point, there is no c[r] left that does not satisfy c[r] > 258 , so the while loop continues forever. 然后每个32个c[r]必须已递增到259在这一点上,不存在c[r]不满足左c[r] > 258 ,所以while循环继续下去。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM