程序给出分段错误

时间:2021-01-22 06:41:29

标签: arrays c pointers

#include <stdio.h>

#include <stdlib.h>

int findMax(int **a, int m, int n)

{

    int max=**a;
    int i,j;
    for (i=0;i<m;i++){
        for (j=0;j<n;j++){
            if (*(*(a+i)+j)>max){
                max=*(*(a+i)+j);
            }
        }
    }

return max;

}
int main()

{ int r,c;

    printf ("Enter the number of rows in the matrix\n");

    scanf (" %d",&r);

    printf ("Enter the number of columns in the matrix\n");

    scanf (" %d",&c);

    printf ("Enter the elements in the matrix\n");

    int **a=(int **) malloc (c*sizeof(int *));
    int i,j;

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

        *(a+i)=(int *) malloc (r*sizeof (int));
    }

    for (i=0;i<r;i++){
        for (j=0;j<c;j++){
            scanf (" %d",(*(a+i)+j));
        }
    }
    printf ("The matrix is\n");

    for (i=0;i<r;i++){
        for (j=0;j<c;j++){
            printf ("%d ",(*(*(a+i)+j)));
        }
    printf ("\n");
}
printf ("The maximum element in the matrix is %d",findMax(a,r,c));
return 0;
}

我试图编写一个代码来查找矩阵中的最大元素

如果我们输入 3 作为行和 2 作为列,则会出现分段错误。也就是写了5个input之后,就突然结束了。

样本输入:

输入矩阵的行数

3

输入矩阵的列数

2

输入矩阵中的元素

2

4

1

3

5

9

此输入失败。 任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

您只是在循环中反转了列和行索引。

以下似乎工作正常:

#include <stdio.h>

#include <stdlib.h>

int findMax(int **a, int m, int n)

{

    int max=**a;
    int i,j;
    for (i=0;i<m;i++){
        for (j=0;j<n;j++){
            if (*(*(a+i)+j)>max){
                max=*(*(a+i)+j);
            }
        }
    }

return max;

}
int main()

{ int r,c;

    printf ("Enter the number of rows in the matrix\n");

    scanf (" %d",&r);

    printf ("Enter the number of columns in the matrix\n");

    scanf (" %d",&c);

    printf ("Enter the elements in the matrix\n");

    int **a=(int **) malloc (c*sizeof(int *));
    int i,j;

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

        *(a+i)=(int *) malloc (r*sizeof (int));
    }

    for (i=0;i<c;i++){
        for (j=0;j<r;j++){
            scanf (" %d",(*(a+i)+j));
        }
    }
    printf ("The matrix is\n");

    for (i=0;i<c;i++){
        for (j=0;j<r;j++){
            printf ("%d ",(*(*(a+i)+j)));
        }
    printf ("\n");
}
printf ("The maximum element in the matrix is %d",findMax(a,c,r));
return 0;
}

顺便说一句,当您使用二维数组时,通常第一个索引是行而不是列。这对于其他开发者的可读性可能很重要。

相关问题