1

我试图洗牌至少一个二维数组的索引,以便我可以总结数组的随机 N 部分。该程序运行良好,直到我尝试调用 shuffle 函数并导致以下两种方式之一:如果我调用该函数:shuffle(a[i], N);,然后我得到一个“浮点异常”错误,即使我似乎找不到任何被 0 分割的部分,或者如果我调用函数:shuffle(*a, N);,我会遇到分段错误。我仍在尝试学习指针的工作原理..有人可以帮忙吗?谢谢!

随机播放功能:

void shuffle(double *a, int i)
{
  int temp, randomNum, N;
  for(i=N; i>1; N--)
     {
        randomNum = rand() % N;
        temp = a[randomNum];   //create temp array
        a[randomNum] = a[i];     
        a[i] = temp; 
      }
}

主程序:

int main()
{

  srand(time(NULL));

  int i,j;
  int M = 5;
  int N = 4;
  double sum = 0.;

  double **a;
  a  = malloc(M * sizeof(double *));

  if(a == NULL) printf("Failure to allocate memory.\n");

  clock_t start = clock();
  for(i=1; i<M; i++)
    {
      a[i] = malloc(M * sizeof(double));
      if( a[i] == NULL)
    {
      printf("Failed to allocated memory for a[%d].\n", i);
      exit(0);
    }
    }

   for(i=1; i<M; i++)
     {
       for(j=1; j<M; j++)
    {
      a[i][j] = 1.0/(i+j);
      printf("a[%d][%d]=%lf\n", i, j, a[i][j]);
      shuffle(a[i], N);
      //sum = sum + a[i][j];
      //printf("shuffleda[%d][%d] and sum = %lf\n", i, j, sum);   
    }
     }

   clock_t end = clock();
   float seconds = (end - start) / (float) CLOCKS_PER_SEC;

   printf("%lf \n", sum);

  return(0);
}
4

1 回答 1

0

void shuffle您的函数中有几个错误。我对该函数进行了一些更正,它对我有用(使用英特尔的 C 编译器):

void shuffle(double a[], int N){
    double temp;
    int randomNum, i;
    for(i=N; i>1; i--){     
        randomNum = rand() % N;
        temp = a[randomNum];   //create temp array
        a[randomNum] = a[i];     
        a[i] = temp; 
    }
}

随着中的shuffle(a[i], N);调用maintemp应该是双精度,而不是int. 浮点异常是由于取模 when N=0

希望这可以帮助。

于 2013-09-30T20:48:24.303 回答