提问人:v_head 提问时间:1/27/2023 最后编辑:Vlad from Moscowv_head 更新时间:1/27/2023 访问量:46
在堆上分配节点,第一次分配给 NULL 和直接分配给 malloc [c] 之间的区别
allocating node on the heap, difference between first assign to NULL and direct assignment with malloc [c]
问:
我正在尝试使用链表实现堆栈,首先我有以下代码:
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;
}
答:
1赞
Vlad from Moscow
1/27/2023
#1
在第一个代码片段中
Node* node = NULL;// allocate a new node in a heap
node = malloc(sizeof * node);
声明的指针将立即被覆盖。node
所以写就足够了
Node* node = malloc(sizeof * node);
如果函数无法分配内存,则返回 null 指针。malloc
请注意,函数名称不明确。inti_stack
2赞
Harith
1/27/2023
#2
在第一种情况下:
Node* node = NULL;// allocate a new node in a heap
node = malloc(sizeof * node);
的值为 dedetermined。 如果成功,将用指向堆内存块的指针覆盖它。node
malloc()
在第二种情况下:
Node* node = malloc(sizeof * node);
的值是不确定的,但它将被覆盖。node
malloc()
所以是的,它们都是等价的。虽然后者是首选。
NB 将在失败时返回指针,并在某些实现上设置。您的代码应该检查它。malloc()
NULL
errno
题外话:为什么没有错误消息?exit()
if (!node) exit(EXIT_FAILURE);
/* I'd expect a fprintf()/perror() here */
评论
Node* node = malloc(sizeof * node);
是初始化,而不是赋值。 也是初始化;不同之处在于它初始化为常量 ()。只有对于在顶层声明的变量,才需要使用常量进行初始化;由于是在函数内部声明的,因此对它被初始化为的值没有限制。Node* node = NULL;
NULL
node