gpt4 book ai didi

c++ - 将复杂的 malloc() 转换为 new() 并建议轻松转换复杂的 malloc 的好方法

转载 作者:太空宇宙 更新时间:2023-11-04 05:16:53 26 4
gpt4 key购买 nike

struct node
{
int data;
node *right,*left;
};

// A queue node
struct Queue
{
int front, rear;
int size;
node* *array;
};

// A utility function to create a new tree node
node* newNode(int data)
{
node* temp = new node();
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}

// A utility function to create a new Queue
Queue* createQueue(int size)
{
Queue* queue = new Queue();

queue->front = queue->rear = -1;
queue->size = size;

**queue->array = (struct node**) malloc(queue->size * sizeof( struct node* ));**

//this is the malloc statement which i want to convert to new;
int i;
for (i = 0; i < size; ++i)
queue->array[i] = NULL;

return queue;
}

我无法将 createQueue 函数中的 malloc() 语句转换为 new();需要帮忙。也请给我建议一个好方法,以便下次将复杂的 malloc() 语句转换为 new()。

最佳答案

您对 malloc 调用所做的是分配指向 node 的指针数组。

要在 C++ 中动态分配数组,您可以使用 new[]

queue->array = new node*[queue->size]{};

上面的语句为node分配了一个queue->size指针数组,并且默认初始化了每个指针,这意味着它们都是空指针(所以分配后不需要循环)。

请记住,您使用 new[] 分配的所有内容都必须使用 delete[] 释放。


现在我们解决了您的问题,正确的解决方案是使用 std::vector而不是像您那样动态分配内存。

我还建议您不要使用指针,而是使用结构的实例。既适用于 vector ,也适用于更一般的情况。除了多态性,在现代 C++ 中很少需要使用指针。

关于c++ - 将复杂的 malloc() 转换为 new() 并建议轻松转换复杂的 malloc 的好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41713389/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com