c - 结构、typedef 和 malloc、calloc

标签 c struct malloc typedef free

我想创建和使用类似的东西:

struct mystruct { 
    mystruct * AnOtherMyStruct; //mystruct must have a pointer to an other mystruct inside
    ...some stuffs...  
};

我应该使用“typedef struct”吗?有哪些优点和缺点?

当我分配内存时,有人告诉我 calloc 比 malloc 好,因为它做同样的工作但更好...

我的结果会是这样的:

struct (or typedef struct) mystruct  {
    mystruct * AnOtherMyStruct;
    ...
};
int main () {

malloc or calloc =...
free(...);

考虑到这些操作会非常频繁地执行,您认为分配和释放结构的最佳选择是什么?

最佳答案

Should I use "typedef struct" or not? Which are the pros and cons ?

这只是主观的编码风格。最常见的样式是使用 typedef。一个优点是它使代码的行为就像 C++。显式输入 struct name 也可以,这是 Linux 喜欢的一种风格。这两种风格都没有明显的对错。

但是,对于自引用结构,无论样式如何,您都必须始终使用 struct 符号编写指针成员。

typedef struct foo
{
  struct foo* next;
} foo_t;

foo_t* next 将不起作用,因为此时 typedef 尚未完成。 foo 然而是一个“结构标签”,而不是类型名称,因此它遵循不同的规则。如果你想在内部使用 typedef 名称,那么你必须转发声明结构:

typedef struct foo foo_t;  // forward declaration
struct foo
{
  foo_t* next;
};

When I allocate memory some told me that calloc is better than malloc because it does the same job but better...

当有人告诉您时,请问他们 calloc 究竟有何改进之处。编程时,批判性思维非常重要。

  • malloc 分配一 block 内存但不将其初始化为已知值。由于没有初始化,malloccalloc 快。
  • calloc 分配一个内存块,或者可选地分配一个放置在相邻内存单元中的 block 数组。它对所有内存进行零初始化,这意味着它具有已知的默认值。因此,它比 malloc 慢。

那么哪个“更好”、更快或预初始化?取决于你想做什么。

关于c - 结构、typedef 和 malloc、calloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59068904/

相关文章:

c - 读取和写入命名管道

c - 结构偏移宏

c - realloc 如何增加内存块的大小?

c - 我是 "have to"free() 静态动态分配指针吗?

c - 将结构传递给函数会产生默认错误

c - 警告 : "assignment discards ' const' qualifier from pointer target type"

c - 如何将变量分配给c中的绝对地址?

c++ - 在 C++ 中将定义的结构转换为 double (复数)

struct - 为什么 `sxhash` 会为所有结构返回一个常量?

ios - 已释放对象的校验和不正确 - 如何在设备上进行故障排除?