将 malloc 转换为新的

Convert malloc to new

本文关键字:转换 malloc      更新时间:2023-10-16

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

#include<alloc>
#define MAXROW 3
#define MAXCOL 5
using namespace std;
int main()
{
    int (*p)[MAXCOL];
    p = (int(*)[MAXCOL])malloc(MAXROW*sizeof(*p));
} 
很简单

,从字面上回答这个问题:

p = new int[MAXROW][MAXCOL];

这会在免费存储上分配一个 2D 数组(MAXROW by MAXCOL),并且像往常一样返回一个new ,返回一个int(*)[MAXCOL] - 与衰减 2D 数组的类型相同。不要忘记delete[] p;.

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

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

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

由于这是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.
} 

字面问题

" 如何使用 new 运算符编写以下代码?

...意味着比你认为它意味着的其他东西。

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

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

不过,对于您的数组,您也不需要它,而只需从标准库中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.
}

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