【发布时间】:2016-03-13 12:21:37
【问题描述】:
我试图在双指针的帮助下找到从 C 函数访问的二维数组中所有值的最大值。 当我运行代码时,它会终止并返回任何值给调用者函数。
我尝试更改代码以打印所有值以找出问题并发现它仅打印以下示例数据的 1 和 2 作为输入。 对于示例代码运行,我提供了 row=2、col=2 和 values=1,2,3,4
请告诉我为什么?另外,如果您的问题不清楚,请说出来。我度过了艰难的一天,所以也许无法更好地解释。
代码有一些限制: 1. 函数签名(int **a,int m,int n)
#include<stdio.h>
int findMax(int **a,int m,int n){
int i,j;
int max=a[0][0];
for(i=0;i<m;i++){
for(j=0;j<n;j++){
if(a[i][j]>max){
max=a[i][j];
}
//printf("\n%d",a[i][j]);
}
}
return max;
}
int main(){
int arr[10][10],i,j,row,col;
printf("Enter the number of rows in the matrix");
scanf("%d",&row);
printf("\nEnter the number of columns in the matrix");
scanf("%d",&col);
printf("\nEnter the elements of the matrix");
for(i=0;i<row;i++){
for(j=0;j<col;j++){
scanf("%d",&arr[i][j]);
}
}
printf("\nThe matrix is\n");
for(i=0;i<row;i++){
for(j=0;j<col;j++){
printf("%d ",arr[i][j]);
}
printf("\n");
}
int *ptr1 = (int *)arr;
printf("\nThe maximum element in the matrix is %d",findMax(&ptr1,row,col));
return 0;
}
【问题讨论】:
-
int **a不是真正的二维阵列。int **a-->int (*a)[10] -
int arr[10][10]l-->int **arr;...arr=malloc(row * sizeof(int*));for(int i=0;i<row;++i)arr[i]=malloc(col * sizeof(int); -
您正在投射
arr,因此您访问不正确。我很惊讶您没有遇到分段错误。删除强制转换并改为修复您的声明以声明正确的指针类型。 -
你的问题的结尾看起来不仅仅是限制。是否允许更改
main中数组的声明/分配? -
@BLUEPIXY 谢谢你的回答。我进行了更改并且效果很好。
标签: c multidimensional-array double-pointer