c++ - C 等同于 C++ delete[] (char *)

标签 c++ c free delete-operator

什么是 C++ 的 C 等价物

delete[] (char *) foo->bar;

编辑:我正在将一些 C++ 代码转换为 ANSI C。它有:

typedef struct keyvalue
{
  char *key;
  void *value;
  struct keyvalue *next;
} keyvalue_rec;

// ...

  for (
    ptr = this->_properties->next, last = this->_properties;
    ptr!=NULL;
    last = ptr, ptr = ptr->next)
  {
    delete[] last->key;
    delete[] (char *) last->value;
    delete last;
  }

这会为 C 做吗?

free(last->key);
free(last->value);
free(last)

最佳答案

在 C 中,您没有 new;你只有 malloc();要释放通过调用 malloc() 获得的内存,将调用 free()

也就是说,为什么要在将指针传递给 delete 之前将其转换为指向 (char*) 的指针?这几乎肯定是错误的:传递给 delete 的指针必须与使用 new 创建的指针类型相同(或者,如果它具有类类型,则为具有虚拟析构函数)。

关于c++ - C 等同于 C++ delete[] (char *),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2966997/

相关文章:

c - 数组 - 错误 : incompatible types in assignment

C:分配给结构的空闲内存不起作用

c++ - 如何在WASAPICaptureSharedEventDriven中以原始格式保存音频文件

c - 整数溢出测试运算符? (&+)

c++ - C++:从vector <byte>的任何位置获取int

c - 试图了解此 C 程序中静态和动态作用域之间的区别

c - 释放结构内的内存时程序崩溃

c - 如何正确释放SDL_ttf分配的资源?

c++ - 这个未定义的行为或实现是否已定义?

C++ 同构管理多种数据类型