[英]Program giving segmentation fault
#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個輸入之后,就突然結束了。
樣本輸入:
輸入矩陣中的行數
3
輸入矩陣中的列數
2
輸入矩陣中的元素
2
4
1
3
5
9
此輸入失敗。 任何幫助將不勝感激。
您只需在循環中反轉列和行索引。
以下似乎工作正常:
#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;
}
在旁注中,當您使用二維 arrays 時,通常第一個索引是行而不是列。 這對於其他開發人員的可讀性可能很重要。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.