将二维数组作为参数传递给函数

Anu*_*wal 5 c++ multidimensional-array

如果我不知道数组的两个维度的大小,并希望使用以下代码打印矩阵

    
    void printAnyMatrix(int (*A)[], int size_A, int size_B)
    {
       for (int i = 0; i<=size_A; i++)
       {
           for (int j = 0; j<=size_B; j++)
               printf("%d ", A[i][j]);
           printf("\n");
       }
       printf("\n");
    }
    
Run Code Online (Sandbox Code Playgroud)

编译器给出

错误无法将'int(*)[(((unsigned int)((int)size_B))+ 1)]'转换为'int()[]'以将参数'1'转换为'void printAnyMatrix(int()[] ,int,int)

iam*_*ind 4

使用template功能来解决此类问题:

template<typename T, unsigned int size_A, unsigned int size_B>
void printAnyMatrix(T  (&Arr)[size_A][size_B])
{       // any type^^  ^^^ pass by reference        
}
Run Code Online (Sandbox Code Playgroud)

size_A现在您可以将任何二维数组传递给此函数,并且大小将以和的形式自动推导size_B

例子:

int ai[3][9];
printAnyMatrix(ai);
...
double ad[18][18];
printAnyMatrix(ad);
Run Code Online (Sandbox Code Playgroud)