繁体   English   中英

使用双指针访问2D数组以使用C语言

[英]Accessing a 2D array using double pointer to function C language

我正在尝试通过双指针从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.函数签名(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中完成此任务的任务留给读者练习。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM