2013-09-30 113 views
1

我想洗牌二维数组的至少一个索引,以便我可以总结一个随机的数组部分。程序工作正常,直到我尝试调用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); 
} 

回答

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

随着在main通话shuffle(a[i], N);temp应该是双精度,而不是int。浮点异常是因为当N=0取模时。

希望这会有所帮助。