2015-11-13 35 views
0

對於這個C代碼,可能有上百種舊式或低效的東西。但主要是,我只想知道爲什麼我在例程「jacobi_solve」中遇到seg錯誤。該驅動程序代碼是在這裏:將數組傳遞給一個函數 - 出了什麼問題?

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


int main() { 
    int m=20, n=20; 
    int i,j; 
    double A[m][n],Anew[m][n]; 

    for (j=0;j<n;j++){ 
    for (i=0;i<m;i++){ 
     A[j][i] = 0.; Anew[j][i] = 0.; 
    } 
    } 

    A[10][10] = 1.; 
    printf("%x\n",A); 

    jacobi_solver(A,Anew,m,n); 

} 

和jacobi_solver是在這裏:

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

void jacobi_solver(double **A, double **Anew, int m, int n) { 

    double err,tol=1.e-6; 
    int iter=0,iter_max=100; 
    int i,j; 

    err = tol*10.; 
    printf("hello\n"); 
    printf("%f %f %d %d\n",err,tol,iter,iter_max); 
    printf("%x\n",A); 
    printf("%f\n",A[10][10]); /* <--- seg fault! */ 
    printf("solving ...\n"); 

    while (err > tol && iter < iter_max) { 

    for(j = 1; j < n-1; j++) { 
     for(i = 1; i < m-1; i++) { 
     Anew[j][i] = 0.25 * (A[j][i+1] + A[j][i-1] + 
          A[j-1][i] + A[j+1][i]); 
     err = fmax(err, abs(Anew[j][i] - A[j][i])); 
     } 
    } 

    printf("%f\n", err); 

    for(j = 1; j < n-1; j++) { 
     for(i = 1; i < m-1; i++) { 
     A[j][i] = Anew[j][i]; 
     } 
    } 


    iter++; 

    } 

} 

需要注意的是,如果我拿走打印語句,我得到一個賽格故障後,在主迴路解決。

+2

'**'是指向指針的指針,而不是指向2D數組的指針。 – Unimportant

+0

這是我總是感到困惑的地方。我認爲數組和指針幾乎是一回事,然後我被告知它們不是。從來沒有真正找出差異。任何好的參考? –

+0

一些很好的答案在這裏:http://stackoverflow.com/questions/1335786/c-differences-between-char-pointer-and-array – Unimportant

回答

2

更改您的求解器功能的東西的界面類似

建議
void jacobi_solver(int m, int n, double A[n][m], double Anew[n][m]) { 
    ... 
} 

一個二維數組應該是公正如此使用。特別的是,它不是一個指向載體的指針表,就像你一樣。數組大小必須先到達,以便可以將它們用於數組參數。

這應該適用於至少符合C99的所有編譯器。

2

代碼是不正確的 - 你不能使用double **,就像你在C中使用二維數組一樣(不像double *和1-D數組,有點令人困惑,但是如果你明白內存是如何工作的話) 。我建議你實現自己的二維數組封裝中的方式之一

How do I work with dynamic multi-dimensional arrays in C?

+0

那麼是否有任何直接的方式將多維數組傳遞給函數?或者這些包裝是唯一的選擇?謝謝。 –

+0

也許這有助於:http://www.geeksforgeeks.org/pass-2d-array-parameter-c/ – Unimportant