c-分段故障(Malloc?)



我正在开发一个使用Jacobi迭代的程序(http://en.wikipedia.org/wiki/Jacobi_iteration)。但我有一个seg错误。代码在我看来是正确的,在这一点上我非常沮丧。也许有人能指出我的错误。

int main(void) {
double* coeff_Matrix;
int nx, ny; 
do{
    //Get values of nx and ny from user.
    printf("Please enter the number of x-points and the number of y-points desired. n");
    printf("n");
    printf("How many x-points do you want? Enter zero for default (1024). n");
    scanf("%d", &nx);
    printf("How many y-points do you want? Enter zero for default (1024). n");
    scanf("%d", &ny);
    coeff_Matrix = NULL;
    coeff_Matrix = (double**) malloc(nx*sizeof(double*)); //SEGMENTATION FAULT DUE TO THIS? 
    if(nx > 0) {
        PDE_calculate(nx, ny, &coeff_Matrix); //This method is used to generate a diagonally dominant matrix.
        jacobi_Calculate(&coeff_Matrix, nx); //This method does the Jacobi iteration.
    }
    else {
        puts("Invalid choice or memory available was exceeded ... Try again.");
            if(coeff_Matrix != NULL) 
            free(coeff_Matrix);
    }
}while(more()); //The more() method just asks the user if they would like to do a different problem. User just says "y/n". Mainly here to allow for expanded functionality.
return 0;

}//结束主

所以,正如你所看到的,程序要求x点和y点。(已经通过#define语句设置了容差。)有什么想法吗?

您似乎混淆了指针的整个概念。

要动态声明大小为(m,n)的多维数组,请执行以下操作:

int **array;
int m=4,n=3,i;
array=malloc(sizeof(int *)*m);
for (i=0;i<m;i++)
    array[i]=malloc(sizeof(int)*n);

因此,这将修改您的程序为:

int main(void) {
double** coeff_Matrix;
int nx, ny, i; 
do{
    //Get values of nx and ny from user.
    printf("Please enter the number of x-points and the number of y-points desired. n");
    printf("n");
    printf("How many x-points do you want? Enter zero for default (1024). n");
    scanf("%d", &nx);
    printf("How many y-points do you want? Enter zero for default (1024). n");
    scanf("%d", &ny);
    coeff_Matrix = NULL;
    coeff_Matrix = (double**) malloc(nx*sizeof(double*)); // you don't need to cast the result of malloc though
    for (i=0;i<nx;i++)
        coeff_Matrix[i]=(double *)malloc(ny*sizeof(double));
    if(nx > 0) {
        PDE_calculate(nx, ny, coeff_Matrix); //This method is used to generate a diagonally dominant matrix.
        jacobi_Calculate(coeff_Matrix, nx); //This method does the Jacobi iteration.
    }
    else {
        puts("Invalid choice or memory available was exceeded ... Try again.");
            if(coeff_Matrix != NULL)
            {
                for (i=0;i<nx;i++)
                    free(coeff_Matrix[i]);
                free(coeff_Matrix);
            }
    }
}while(more()); //The more() method just asks the user if they would like to do a different problem. User just says "y/n". Mainly here to allow for expanded functionality.
return 0;
}
 coeff_Matrix = (double**) malloc(nx*sizeof(double*));

您不需要键入从malloc返回的指针。显式键入强制类型转换被认为不是一种好的做法。如果使用类型强制转换,它也应该是double *。但显式键入强制类型不是一种好的做法。所以最好只是将CCD_ 3的输出分配给一个指针。类型转换将被隐式处理。

相关内容

  • 没有找到相关文章

最新更新