繁体   English   中英

malloc的以下代码行是什么?

[英]What the following line of code with malloc does?

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

#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中使用malloc时进行转换是没有必要的。 (见这里

您正在进行mallocing,因为您正在分配节点结构大小的堆内存。 你在C中看到,你必须记住所有变量的存储位置。 stackheap (见这里

在函数内部,您的变量称为局部变量 ,存储在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_strsome_str_func()是(在函数的栈IE) 返回一个局部变量的函数。 由于一旦你离开函数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的“C编程语言”是一个非常好的参考,但更现代和图形化(甚至有趣的阅读!认真)的书是Head First C David和Dawn Griffiths解释了许多重要的C概念,例如Heap和Stack,动态和静态C库之间的区别,为什么使用Makefiles是一个好主意,Make如何工作,以及之前没有解释的更多概念常见的C书,绝对值得一看。

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

阅读: void *malloc(size_t size);

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

因此,在

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

你正在分配size = sizeof naode字节的内存块和从存储在node指针中的malloc返回的地址。

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

附注:避免不通过malloc和calloc函数转换返回地址是安全的。 阅读: 我是否施放了malloc的结果?

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

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

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

使用sizeof -

sizeofT )将告诉存储类型为T的变量所需的字节数

使用malloc -

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

使用( struct node* ) -

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

void* malloc (size_t size);

分配内存块

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

并且不要转换malloc的结果。

你还需要释放这个记忆:

void free (void* ptr);

释放内存块

先前通过调用malloc,calloc或realloc分配的内存块被释放,使其再次可用于进一步分配。

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

指针就像一个街道地址,站在地址上的建筑物是由malloc构建的 - 或者至少是构建建筑物所需的大小 - 你在那里建造的东西取决于你。

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

二叉树将使用malloc分配它的每个节点,在内存中是无关紧要的,并且可能是用malloc和指针理解有点棘手的东西。 只要有指向这些位置的指针一切都很好。

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

占用足够的空间来容纳node结构

暂无
暂无

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

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