使用指向函数C语言的双指针访问2D数组

时间:2016-03-13 12:21:37

标签: c multidimensional-array double-pointer

我试图在双指针的帮助下找到从C函数访问的2D数组中的所有值的最大值。 当我运行代码时,它会终止并返回任何值给调用者函数。

我尝试更改代码以打印所有值以找出问题,并发现它只打印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;
}

1 个答案:

答案 0 :(得分:0)

  

代码有一些限制:1。函数签名(int ** a,int m,int n)

我猜你的任务是使用一个指针数组,所有指针都指向分配?

#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;
}

在一个malloc中完成这项工作的任务留给了读者。

相关问题