【问题标题】:allocating node on the heap, difference between first assign to NULL and direct assignment with malloc [c]在堆上分配节点,首先分配给 NULL 和使用 malloc [c] 直接分配之间的区别
【发布时间】:2023-01-27 00:54:36
【问题描述】:

我正在尝试使用链表实现一个堆栈,首先我有以下代码:

typedef struct Node {
    int data;               // integer data
    struct Node* next;      // pointer to the next node
} Node;


Node* inti_stack() {
    Node* node = NULL;// allocate a new node in a heap
    node = malloc(sizeof * node);
    if (!node) exit(EXIT_FAILURE);
    return node;
}

对于 inti_stack 函数,我可以只执行以下操作吗?

Node* inti_stack() {
    Node* node = malloc(sizeof * node);
    if (!node) exit(EXIT_FAILURE);
    return node;
}

【问题讨论】:

    标签: c data-structures linked-list stack


    【解决方案1】:

    在第一个代码中

    Node* node = NULL;// allocate a new node in a heap
    node = malloc(sizeof * node);
    

    声明的指针节点立即被覆盖。

    所以写就够了

    Node* node = malloc(sizeof * node);
    

    如果函数 malloc 无法分配内存,它会返回一个空指针。

    注意inti_stack函数名不清楚。

    【讨论】:

      猜你喜欢
      • 2014-01-26
      • 2011-01-13
      • 1970-01-01
      • 2016-04-13
      • 2020-08-24
      • 1970-01-01
      • 1970-01-01
      • 2012-01-18
      • 2014-03-05
      相关资源
      最近更新 更多