将 malloc 转换为新的
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));
}
,从字面上回答这个问题:
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::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.
}
字面问题
" 如何使用 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 库提供了一个矩阵类。
- 如果没有malloc,链表实现将失败
- 防止主数据类型C++的隐式转换
- 模板参数替换失败,并且未完成隐式转换
- 努力将整数转换为链表。不知道我在这里做错了什么
- HEX值到wchar_t字符(UTF-8)的转换
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将 malloc 转换为新的正确方法
- 将 C 代码移植到C++,将 void* 从 malloc 转换为所需指针的问题
- 将 malloc 转换为新的或 std::vector
- x = malloc(n * sizeof (int));无法将 void 转换为 int
- 数据类型(从 malloc 返回)是如何转换的?
- 如何使用malloc从一维数组转换为二维数组
- 如何使用 malloc() 将 C 语句转换为 C++
- 为什么 new 不需要强制转换为指针,即使 malloc 需要它?
- 在汇编中使用malloc分配的内存-希望在c++中将其转换为三维数组
- 避免c++中的malloc:从' void* '到' uv_loop_t* '的无效转换
- 将static_cast<字符 *>malloc/free/free转换为新的/删除
- 将malloc转换为新的c++ for结构体
- 类型转换malloc c++
- 将 malloc 转换为新的