简体   繁体   English

C等效于C ++ delete [](字符*)

[英]C equivalent of C++ delete[] (char *)

What is the C equivalent of C++ 什么是C ++的C等价物

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

Edit: I'm converting some C++ code to ANSI C. And it had: 编辑:我正在将一些C ++代码转换为ANSIC。它具有:

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;
  }

Would this do it for C ? 这对C有用吗?

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

In C, you don't have new ; 在C语言中,您没有new ; you just have malloc() ; 你只有malloc() ; to free memory obtained by a call to malloc() , free() is called. 为了释放通过调用malloc()获得的内存,将调用free()

That said, why would you cast a pointer to (char*) before passing it to delete ? 也就是说,为什么要在将指针传递给(char*)之前将其转换为delete That's almost certainly wrong: the pointer passed to delete must be of the same type as created with new (or, if it has class type, then of a base class with a virtual destructor). 几乎可以肯定这是错误的:传递给delete的指针必须与使用new创建的指针具有相同的类型(或者,如果具有类类型,则具有虚拟析构函数的基类)。

Just plain 'ol free() . 只是普通的ol free() C makes no distinction between arrays and individual variables. C在数组和单个变量之间没有区别。

相当于deletedelete[]的C语言是free吗?

与非数组相同。

free(foo->bar)

The equivalent would be: 等效为:

free(foo->bar); free(foo-> bar);

since you were typecasting it to (char *) which means whatever the actual type of 'bar' was there would have been no destructor called as a result of the cast. 因为您将其类型转换为(char *),这意味着无论'bar'的实际类型是什么,都不会因强制转换而调用析构函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM