c++ - 矩阵指针语法

标签 c++ pointers syntax matrix

我的问题是为什么他们在 matrix 指针的声明中使用 (int**) 作为指向数组的指针。有必要吗?这有什么区别?

#include <iostream>
using namespace std;
int main()
{
    int **matrix;       // Pointer to matrix
    matrix = (int **) new int *[2]; // Why use (int**) is it necessary?
    for (i = 0; i < 2; i++)
        matrix[i] = new int[2];
    for (i = 0; i < 2; i++)
        for (int j = 0; j < 2; j++) {
            matrix[i][j] = j + i;
        }
}

最佳答案

这是不必要的,而且有潜在危险。

new-expression的类型已经是int**,适合赋值给matrix。无需将其转换为自己的类型。

即使需要转换,也不应使用 C 风格的转换。这样做会强制转换,即使它没有任何意义,这是一个很好的隐藏错误的方法;例如,如果您不小心 new 类型错误:

matrix = new int[2];           // Friendly compiler error
matrix = (int**) new int[2];   // No diagnostic, likely to cause weird
                               // run-time errors.

关于c++ - 矩阵指针语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13796756/

相关文章:

c++ - boost::shared_ptr::shared_ptr(const boost::shared_ptr&)' 被隐式声明为已删除

c++ - QT造物主: Cannot include functions from other files in QT Creator c project

c++ - 设置控制台文本属性 : Foreground only

c++ - 明确的特化; 'std::hash<_Kty>' 已经实例化

c++ - 指针和 char*

sql-server - 微软 SQL 错误 :Incorrect syntax near the keyword 'on'

Java native 访问代码错误 : "Invalid memory access"

c - 结构列表中的内存错误(存储未知)

C++ WCHAR : Cannot allocate an array of constant size 0

javascript - 为什么我看到 javascript 数组是用 string.split() 创建的?