如何使用new运算符编写以下代码? 请详细解释。 提前谢谢。
#include<alloc>
#define MAXROW 3
#define MAXCOL 5
using namespace std;
int main()
{
int (*p)[MAXCOL];
p = (int(*)[MAXCOL])malloc(MAXROW*sizeof(*p));
}
答案 0 :(得分:2)
很简单,按字面意思回答这个问题:
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>
也可以在这里工作。这通常比动态分配更好。
如果在编译时都不知道维度,那么最好的选择通常是向量向量或专用矩阵类,以便在知道每个内部向量大小相同时提高性能。
答案 1 :(得分:1)
字面问题
“如何使用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库提供了一个矩阵类。
答案 2 :(得分:1)
由于这是C ++,我将使用std::array
和std::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.
}