将 malloc 转换为 new

Convert malloc to new

如何使用new运算符编写以下代码? 请详细说明。 提前致谢。

#include<alloc>
#define MAXROW 3
#define MAXCOL 5
using namespace std;

int main()
{
    int (*p)[MAXCOL];
    p = (int(*)[MAXCOL])malloc(MAXROW*sizeof(*p));
} 

字面问题

How to write the following code using new operator?

... 意思与您认为的不同。

new运算符是一个简单的分配函数,大致直接类似于C的malloc,除了C++ new 运算符可由用户定义的运算符替换。

您的意思可能是 new 表达式。这样的表达式调用 new 运算符进行分配,如果分配的东西是 class 类型,则 然后调用构造函数进行初始化。而且它是类型安全的。

不过,对于您的阵列,您也不需要它,而只是标准库中的 std::vector


下面是一个使用 std::vector 向量创建矩阵的示例:

#include <vector>
using namespace std;

auto main()
    -> int
{
    int const n_rows = 3;
    int const n_cols = 5;

    using Row = vector<int>;

    vector<Row> v( n_rows, Row( n_cols ) );

    // E.g. v[1] is a row, and v[1][2] is an int item in that row.
}

即使您不经常使用矩阵,将矩阵的一般概念包装在 class 中也是一个好主意。一种简单的方法是使用单个 std::vector 进行存储,并提供例如at 函数或 operator() 用于从客户端代码进行索引。如果您还不想自己这样做,那么例如Boost库提供了一个矩阵class.

由于这是 C++,我建议使用 std::arraystd::unique_ptr 此外,当使用 malloc 时,您应该使用 free 取消分配或释放内存,如果您使用 new,则需要使用 delete;如果你 new[] 你需要使用 delete[]

#include <cstdlib>
#include <memory>
#include <array>
#define MAXROW 3
#define MAXCOL 5
using namespace std;

int main()
{
    int (*p)[MAXCOL];
    p = (int(*)[MAXCOL])malloc(MAXROW*sizeof(*p));
    free(p); //free memory 
    array<int,MAXCOL> *p1 = new array<int,MAXCOL>[MAXROW];
    delete []p1; //use this to delete the variable
    array<array<int,MAXCOL>,MAXROW> *p2 = new array<array<int,MAXCOL>,MAXROW>;
    delete p2;  // normal delete for this one
    auto p3 = make_unique<array<array<int,MAXCOL>,MAXROW>>();
    //no delete needed for p3, it is a smart pointer.
} 

很简单,从字面上回答问题:

p = new int[MAXROW][MAXCOL];

这会在自由存储上分配一个二维数组(MAXROW by MAXCOL),并且像往常一样使用 new、returns 一个 int(*)[MAXCOL] - 与衰减二维数组的类型相同.别忘了 delete[] p;.

最后一部分提出了 std::vector 的重要性。据推测,您在编译时就知道第二个维度的大小。因此,std::vector<std::array<int, MAXCOL>> 可以使用不需要 delete[] 语句的额外好处,而且它知道它的大小 (MAXROW)。请尽可能使用它。

事实上,在您的示例中,两个维度在编译时都是已知的,这意味着 std::array<std::array<int, MAXCOL>, MAXROW> 也可以在这里工作。这通常比动态分配更可取。

如果在编译时两个维度都未知,那么最好的选择通常是向量的向量或专用矩阵 class 以在您知道每个内部向量的大小相同时提高性能。