gpt4 book ai didi

c - 结构、typedef 和 malloc、calloc

转载 作者:行者123 更新时间:2023-12-04 11:36:29 25 4
gpt4 key购买 nike

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

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/

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