如何在代码中使用"new"而不是"malloc"

How to use 'new' insted of 'malloc' in code

本文关键字:new malloc 代码      更新时间:2023-10-16

我的代码如下所示

SP->xs = malloc(size * sizeof(double));

其中xs是结构变量,sizeint类型,

所以在这里我如何使用new而不是malloc

我应该包含哪个头文件? 以及这个新行的语法将如何变成?

我只是像下面一样尝试了一下

SP->xs = operator new sizeof(double)*[size];

当我编译此代码时,会出现如下错误

error: cannot resolve overloaded function 'operator new' based on conversion to type 'double*'
error: expected ';' before 'sizeof'

因为我是新手C++所以我不知道更多细节,

所以请描述我如何在我的代码中使用new而不是malloc

感谢和问候

相当于

SP->xs = malloc(size * sizeof(double));

SP->xs = new double[size];

这不需要任何#include

要释放分配的数组,请使用delete[]

delete[] SP->xs;

方括号很重要:没有它们,代码将编译,但将具有未定义的行为。

由于您是用C++编写的,请考虑使用 std::vector<double> 而不是手动管理内存分配。