结构,typedef和malloc,calloc

我想创建和使用类似以下内容:

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(...);

您认为,考虑到这些操作将非常频繁地进行,这是分配和取消分配结构的最佳选择?

wgzh107109 回答:结构,typedef和malloc,calloc

calloc()malloc()几乎相同。

calloc()0初始化声明的内存。

当您调用malloc()并尝试访问已分配类型的成员时,在使用{{时,您将看到垃圾值(例如对于int,您将看到类似347289472的值) 1}},您将看到0作为初始值

,
  

是否应该使用“ typedef struct”?优点和缺点是哪些?

这只是主观的编码风格。最常见的样式是使用typedef。优点之一是它使代码的行为类似于C ++。明确地键入<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <ScrollView android:layout_width="match_parent" android:layout_height="match_parent" android:fillViewport="true"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/signup_background" android:orientation="vertical" android:padding="40dp"> ... </LinearLayout> </ScrollView> </RelativeLayout> 也可以,这是Linux所偏爱的样式。两种风格都不是对还是错。

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

struct

typedef struct foo { struct foo* next; } foo_t; 将不起作用,因为此时typedef不完整。 foo_t* next是一个“结构标记”,而不是类型名称,因此它遵循不同的规则。如果希望在内部使用typedef名称,则必须向前声明该结构:

foo

  

当我分配内存时,有人告诉我calloc比malloc好,因为它可以完成相同的工作,但效果更好...

有人告诉你,问他们typedef struct foo foo_t; // forward declaration struct foo { foo_t* next; }; 到底有多好。在编程时,批判性思维非常重要。

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

那么,哪个“更好”,更快或预先初始化?取决于您要做什么。

本文链接:https://www.f2er.com/3022201.html

大家都在问