【问题标题】:What the following line of code with malloc does?以下带有 malloc 的代码行是做什么的?
【发布时间】:2013-09-21 18:15:01
【问题描述】:

我有以下实现来镜像二叉树。

#include<stdio.h>
#include<stdlib.h>

/* A binary tree node has data, pointer to left child
   and a pointer to right child */
struct node
{
    int data;
    struct node* left;
    struct node* right;
};

/* Helper function that allocates a new node with the
   given data and NULL left and right pointers. */
struct node* newNode(int data)

{
  struct node* node = (struct node*)
                       malloc(sizeof(struct node));
  node->data = data;
  node->left = NULL;
  node->right = NULL;

  return(node);
}


/* Change a tree so that the roles of the  left and
    right pointers are swapped at every node.

 So the tree...
       4
      / \
     2   5
    / \
   1   3

 is changed to...
       4
      / \
     5   2
        / \
       3   1
*/
void mirror(struct node* node)
{
  if (node==NULL)
    return; 
  else
  {
    struct node* temp;

    /* do the subtrees */
    mirror(node->left);
    mirror(node->right);

    /* swap the pointers in this node */
    temp        = node->left;
    node->left  = node->right;
    node->right = temp;
  }
}


/* Helper function to test mirror(). Given a binary
   search tree, print out its data elements in
   increasing sorted order.*/
void inOrder(struct node* node)
{
  if (node == NULL)
    return;

  inOrder(node->left);
  printf("%d ", node->data);

  inOrder(node->right);
} 


/* Driver program to test mirror() */
int main()
{
  struct node *root = newNode(1);
  root->left        = newNode(2);
  root->right       = newNode(3);
  root->left->left  = newNode(4);
  root->left->right = newNode(5);

  /* Print inorder traversal of the input tree */
  printf("\n Inorder traversal of the constructed tree is \n");
  inOrder(root);

  /* Convert tree to its mirror */
  mirror(root);

  /* Print inorder traversal of the mirror tree */
  printf("\n Inorder traversal of the mirror tree is \n"); 
  inOrder(root);

  getchar();
  return 0; 
}

我说的是下面一行:

  struct node* node = (struct node*)
                       malloc(sizeof(struct node));

我有 c/c++ 的中级知识,但我很害怕指针。即使经过几次尝试,我也从未能够得到指针。我尽可能避免使用它们,但是在实现像树这样的数据结构时,没有其他选择。为什么我们在这里使用 malloc 和 sizeof?还有我们为什么要强制转换 (struct node*)?

【问题讨论】:

  • 检查答案。如果您发现任何遗漏,请随时询问。

标签: c pointers malloc sizeof


【解决方案1】:

首先,在 C 中使用 malloc 时不需要强制转换。 (见here

您正在 malloc-ing,因为您正在分配节点结构大小的堆内存。您在 C 中看到,您必须记住所有变量的存储位置。即stackheap(见here

在函数内部,您的变量称为局部变量,存储在stack 中。一旦你离开函数,堆栈中的变量就会被清除。

为了能够在函数之外引用或使用局部变量,您必须在heap 中分配内存,这就是您在此处所做的。您在堆中分配内存,以便您可以在其他函数中重用相同的变量。

总结:

  • 函数内的变量是函数的局部变量,因此称为局部变量
  • 要让其他函数访问局部变量,您必须在堆中分配内存以与其他函数共享该变量。

举个例子,看看下面的代码:

#include <stdio.h>
#include <string.h>

char *some_string_func()
{
    char some_str[13]; /* 12 chars (for "Hello World!") + 1 null '\0' char */

    strcpy(some_str, "Hello World!");

    return some_str;
}

int main()
{
    printf("%s\n", some_string_func());
    return 0;
}

很简单,main 只是调用一个函数some_str_func,它返回一个局部变量some_str,编译上面的代码可以工作,但并非没有警告:

test.c: In function ‘some_string_func’:
test.c:11:9: warning: function returns address of local variable [enabled by default]

虽然它编译注意到some_str_func() 中的some_str返回一个局部变量 给函数(即在函数的堆栈中)。因为一旦您离开函数some_str_func(),堆栈就会被清除,因此在main()不可能获取some_str 的内容,即“Hello World”。

如果你尝试运行它,你会得到:

$ gcc test.c
$ ./a.out

$

它什么也不打印,因为它无法访问some_str。为了解决这个问题,您可以为字符串“Hello World”分配一些内存空间。像这样:

#include <stdio.h>
#include <string.h>

char *some_string_func()
{
    char *some_str;

    /* allocate 12 chars (for "Hello World!") + 1 null '\0' char */
    some_str = calloc(13, sizeof(char));

    strcpy(some_str, "Hello World!");

    return some_str;
}

int main()
{
    char *str = some_string_func();
    printf("%s\n", str);

    free(str);  /* remember to free the allocated memory */
    return 0;
}

现在当你编译并运行它时,你会得到:

$ gcc test.c
$ ./a.out
Hello World!
$

如果您很难理解 C,我知道很多人会发现 Brian W. Kernighan 和 Dennis Ritchie 的“The C Programming Language”是一本非常好的参考书,但它更现代和图形化(阅读起来甚至很有趣!认真) 这本书是 Head First C 由 David 和 Dawn Griffiths 撰写,他们解释了许多重要的 C 概念,例如堆和堆栈,动态和静态 C 库之间的区别,为什么使用 Makefiles 是一个好主意,Make 如何工作,以及更多以前在普通 C 书籍中没有解释过的概念,绝对值得一看。

另一个很好的在线资源是 Zed Shaws Learn C the Hard way,他在其中提供了很好的代码示例和注释。

【讨论】:

  • 和我们在 C++ 或 Java 中使用 new 有什么不同?
  • @user1425223 malloc 的结果是指向未初始化内存的指针。不像new。你可以说new T(args) ~= malloc(sizeof(T)) + T(args)
  • 值得一提的是,标准中没有提到所有关于“堆”和“堆栈”的内容。例如,在某些嵌入式平台上,没有堆,malloc() simlu 返回一个指向“一些不是堆栈的内存”的指针(例如,参见 AVR-libc 中 malloc() 的实现)。跨度>
  • Chutsu 小问题如果你使用strcpy(),你不需要明确终止字符串,所以从代码中删除some_str[12] = '\0'; /* remember to null terminate */。反正很好的答案。
  • 更新了答案,@GrijeshChauhan 感谢您的提醒:)
【解决方案2】:

阅读:void *malloc(size_t size);

malloc() 函数分配size 字节并返回一个指向 分配的内存。内存未初始化。如果大小为 0, 然后malloc() 返回NULL,或者一个唯一的指针值,它可以 稍后成功传递给free()

因此,在

struct node* node = (struct node*)malloc(sizeof(struct node));
  //                                     ^----size---------^

您正在分配 size = sizeof naode 字节的内存块,并从存储在 nodepointer 中的 malloc 返回地址。

注意你有错误变量名不应该是node,因为它是结构名。你可以!但不是很好的做法。此外,sizeof(*pointer) 优先于 sizeof(Type),以防类型发生更改

旁注:避免不通过 malloc 和 calloc 函数转换返回地址是安全的。阅读:Do I cast the result of malloc?

所以正确上述陈述的优选形式是:

struct node* nd = malloc(sizeof *nd);
  //                     ^----size-^

两个更正:(1)删除类型转换和(2)将变量名更改为nd

【讨论】:

  • "你有错误的变量名不能是节点,因为它是结构名。" - 他可以。不过,这不是很好的做法。此外,sizeof(*pointer) 优先于 sizeof(Type),以防类型发生更改。
  • @H2CO3 是吗?? ... 有趣的。我再次向您复制 :) 谢谢!
  • @H2CO3 非常感谢 H2co3 人。接下来它在 C++ 中不应该是正确的,因为在 C++ 中我们可以使用没有 struct 关键字的结构名称。我正确吗?
  • @H2CO3 在 C++ 类命名空间和变量命名空间中得到它是不同的。好男人!
  • @Elazar 对不起我没试过我从here学到的请检查并建议纠正。
【解决方案3】:

使用sizeof-

sizeof(T) 将告诉存储 T

类型的变量所需的字节数

使用malloc-

Malloc 动态分配内存,即在运行时(当您的程序实际由 CPU 执行时,它在内存中)。当我们不确定运行时所需的内存量时,我们主要使用它。所以我们在运行时使用malloc动态分配它。

使用 (struct node*)-

Malloc 返回一个指向内存块的指针,其中包含您要求的空间量(在其参数中)。这个空间只是内存中的一些空间。因此,该指针没有与之关联的类型。我们将此指针强制转换为 (struct node*),因为它会让机器知道 (struct node) 类型的变量将保存在此内存中。

【讨论】:

    【解决方案4】:
    void* malloc (size_t size);
    

    分配内存块

    分配一块大小字节的内存,返回一个指向 块的开始。新分配块的内容 内存未初始化,剩余的值不确定。如果 大小为零,返回值取决于特定的库 实现(它可能是也可能不是空指针),但返回 指针不应被取消引用。

    并且不要转换malloc的结果。

    你还需要释放这个内存:

    void free (void* ptr);
    

    释放内存块

    先前通过调用 malloc、calloc 或 realloc 被释放,使其再次可用 分配。

    【讨论】:

      【解决方案5】:

      你使用 malloc 通常让指针有指向的东西。

      指针就像街道地址,位于该地址上的建筑物是由 malloc 建造的——或者至少是建造建筑物所需的大小——你在那里建造什么由你决定。

      在您的示例中,树中的每个节点都是用 malloc 分配的字节数,节点的大小是保存节点所有内容所需的字节数。

      二叉树将为其每个节点分配 malloc,其中在内存中是无关紧要的,这可能是使用 malloc 和指针有点难以理解的事情。只要有指向这些位置的指针,一切都很好。

      【讨论】:

        【解决方案6】:
        struct node* node = (struct node*)malloc(sizeof(struct node)); 
        

        分配足够的空间来容纳node 结构

        【讨论】:

          猜你喜欢
          • 2014-08-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-02-21
          • 1970-01-01
          • 2015-12-23
          • 2015-01-14
          • 1970-01-01
          相关资源
          最近更新 更多