更正为char *数组使用new的语法

时间:2014-02-19 21:16:14

标签: c++ memory-management malloc

我有以下

typedef struct
{
    int        titleCount; 
    char**     titles;
} myStruct;

然后

...
struct1->titleCount = 2;
struct1->titles = (char**) malloc(sizeof(char *) * (str->titleCount + 1));
...

使用new代替malloc的正确语法是什么?

3 个答案:

答案 0 :(得分:3)

在示例中,titles指向char的指针数组,或者很可能实际上是字符串。所以我希望有类似的东西:

titles = new char*[str->titleCount]; // or maybe keep the +1

后跟一个循环来分配各个字符串,并将指针放入标题所指向的数组中。

答案 1 :(得分:2)

如果要从C移植到C ++,更好的解决方案是:

std::vector<std::string> myTitles;

整个结构是不必要的。

答案 2 :(得分:0)

首先,您分配内存的代码无效,因为您可能无法编写

struct1->titleCount 

除非你写的地方

struct struct1 *struct1 = malloc( sizeof( struct struct1 ) );

但是从您提供的代码中看来,您需要分配

str->titleCount + 1

char *

类型的元素

因此相应的代码将显示为

str->titleCount = 2;
str->titles = new char * [str->titleCount + 1];

下次请显示可编译的代码段。从你的代码来看,不清楚struct1和str是什么。你只会混淆别人。