【问题标题】:Passing two dimensional array in a function as parameter在函数中传递二维数组作为参数
【发布时间】:2021-10-17 17:00:16
【问题描述】:
#include<stdio.h>

void print(int r, int c, int Ar[][c])
{
    int i,j;
    printf("\n");
    for(i=0;i<r;i++)
    {
        for(j=0;j<c;j++)
        printf("%d ",Ar[i][j]);
        printf("\n");
    }
}

int main()
{
  int m,n,i,j;
  int A[100][100];
 
  printf("Enter number of rows and columns matrix: ");
  scanf("%d%d", &m, &n);
  printf("Enter elements of first matrix:\n");
  for (i=0;i<m;i++)
  {
    for (j=0;j<n;j++)
    scanf("%d",&A[i][j]);
  }
  print(m,n,A);
  return 0;
}

输出: 输入行数和列数矩阵:2 3 输入第一个矩阵的元素: 2 1 3 5 4 6

2 1 3 0 0 0

为什么不打印第二行?

【问题讨论】:

标签: arrays c function 2d


【解决方案1】:

以下程序仅在您的编译器兼容 C99 时才有效。

#include <stdio.h>
 
// n must be passed before the 2D array
void print(int m, int n, int arr[][n])
{
    int i, j;
    for (i = 0; i < m; i++)
      for (j = 0; j < n; j++)
        printf("%d ", arr[i][j]);
}
 
int main()
{
    int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    int m = 3, n = 3;
    print(m, n, arr);
    return 0;
}

【讨论】:

    【解决方案2】:

    编辑:这个问题之前被标记为 C++。 . .


    如果你想将一个普通的旧 C 数组传递给一个函数,你有两种可能性。

    1. 通过引用传递
    2. 按指针传递

    你用过的,连编译都没有。

    在 C++ 中,数组必须具有编译时已知的大小。

    请看:

    void function1(int(&m)[3][4])   // For passing array by reference
    {}
    void function2(int(*m)[3][4])   // For passing array by pointer
    {}
    
    int main()
    {
        int matrix[3][4]; // Define 2 dimensional array
    
        function1(matrix);  // Call by reference
        function2(&matrix); // Call via pointer 
        return 0;
    }
    

    无论如何。使用像 std::arraystd::vector 这样的现代 c++ 容器几乎总是更好的解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-22
      • 1970-01-01
      • 2020-10-04
      • 2015-08-23
      • 2022-07-25
      • 1970-01-01
      相关资源
      最近更新 更多