问题
I am trying to find the maximum of all values in a 2D array accessed from a C function with the help of double pointer. When I run the code it just terminates with returning any value to the caller function.
I tried to change the code to print all values to find out the problem and found that it only prints 1 and 2 for the following sample data as input. For a sample code run, I provided row=2, col=2 and values=1,2,3,4
Please let me know why? Also if you question is not clear please say so. I've had a tough day so maybe couldn't explain better.
There is a few restrictions to the code: 1. Function Signature(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;
}
回答1:
There is a few restrictions to the code: 1. Function Signature(int **a,int m,int n)
I guess your task is therefore to use an array of pointers, all of which point to allocations?
#include<stdio.h>
#include<stdlib.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;
int 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);
arr = malloc(row * sizeof(int*));
if (!arr)
{
printf("arr not malloc'd\n");
abort();
}
for(i=0;i<row;i++)
{
arr[i] = malloc(col * sizeof(int));
if (!arr[i])
{
printf("arr[%d] not malloc'd\n", i);
abort();
}
for(j=0;j<col;j++)
{
arr[i][j] = 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");
}
printf("\nThe maximum element in the matrix is %d",findMax(arr, row, col));
return 0;
}
The task of doing it in a single malloc is left as an exercise to the reader.
来源:https://stackoverflow.com/questions/35970159/accessing-a-2d-array-using-double-pointer-to-function-c-language