【问题标题】:C++ generalize two dimension array in functionC++函数中的广义二维数组
【发布时间】:2019-12-19 05:39:14
【问题描述】:

我想用 C++ 编写一个函数,它可以获取任意大小的矩阵并打印出来。

我的代码如下,它可以工作。但我的问题:

1) 这是最佳实践吗? 2) 为什么使用(int *) 进行投射而static_cast<int *> 不起作用?

谢谢

#include <iostream>

using namespace std;

void print_matrix(int *, int, int);

int main()
{
    int mat[3][3] = {{1, 2, 3},
                    {4, 5, 6},
                    {7, 8, 9}
    };

    int mat2[5][5] = {{1, 2, 3, 40, 50},
                    {4, 5, 6, 70, 80},
                    {7, 8, 9, 10, 20},
                    {17, 18, 19, 10, 20},
                    {71, 81, 91, 110, 120}
    };

    print_matrix((int *)mat2, 5, 5);
    cout << endl;

    print_matrix((int *)(mat), 3, 3);
    cout << endl;

//    static cast does not work:
//    error: invalid static_cast from type 'int [3][3]' to type 'int*'|
//    print_matrix(static_cast<int *>(mat), 3, 3);

    return 0;
}

void print_matrix(int *matPtr, int row, int col)
{
    for(int i = 0; i < row; i++) {
        for(int j = 0; j < col; j++)
            cout << *(matPtr + col * i + j) << '\t';
        cout << endl;
    }
}

【问题讨论】:

  • 这是未定义的行为,您可以越界访问该行(这就是 mat2,又名。&amp;mat2[0] 得到您)

标签: c++ function multidimensional-array


【解决方案1】:

这是最佳实践吗?

不,不是。

使用函数模板会更好。

template <size_t NR, size_t NC>
void print_matrix(int (&matrix)[NR][NC])
{
   ...
}

并将其称为:

print_matrix(mat2); // NR and NC are deduced by the compiler

为什么使用(int *) 进行投射但static_cast&lt;int *&gt; 不起作用?

给定

int mat[3][3] = { ... };

以下指针具有相同的数值,即使指针类型不同。

int (*p1)[3][3] = &mat;
int (*p2)[3] = &mat[0];
int *p3 = &mat[0][0];

由于这种巧合,使用(int*) 有效。

使用static_cast&lt;int*&gt; 不起作用,因为当二维数组衰减到指针时,它不会衰减到int* -- mat 衰减到 int (*)[3](指向“3 个 ints 的数组”的指针) ") 和 mat2 衰减到 int (*)[5](指向“5 个 ints 的数组”的指针)。它们一般不能转换为int*

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-27
    • 2019-03-02
    • 2021-12-04
    相关资源
    最近更新 更多