【发布时间】:2020-11-21 11:42:08
【问题描述】:
在 C 中进行编码练习时,我必须为指向结构的指针 (cur) 分配内存,即使该结构可能已经为其预先分配了内存,否则我会得到一个“分配给空指针的错误类型。
我假设如果指针要指向具有预分配内存的结构,那么分配更多内存会是多余的吗?为了澄清,代码编译和运行没有错误,只是对我为什么需要分配内存来实现预期的行为感到困惑。
/* create a stack */
typedef struct {
int top;
struct TreeNode array[MAX_ARR_SIZE];
} Stack;
int node_comparator(const void *p, const void *q);
struct TreeNode *increasingBST(struct TreeNode *root) {
/* add all the nodes to an array via DFT */
int i, sorted_pos = 0;
struct TreeNode *start, *cur;
struct TreeNode sorted_nodes[MAX_ARR_SIZE];
Stack *node_stack = malloc(sizeof(Stack));
node_stack->top = -1;
node_stack->array[++node_stack->top] = *root;
/* below is the pointer in question
* originally, this line was not here */
cur = malloc(sizeof(struct TreeNode));
while (node_stack->top != -1) {
/* "pop" node off stack */
*cur = node_stack->array[node_stack->top--];
/* add node to array */
sorted_nodes[sorted_pos++] = *cur;
/* add right and left node to stack, if present */
if (cur->right != NULL)
node_stack->array[++node_stack->top] = *cur->right;
if (cur->left != NULL)
node_stack->array[++node_stack->top] = *cur->left;
}
/* etc... */
这里有一个link 以获取完整上下文的要点。谢谢!
【问题讨论】:
-
“预分配内存”是什么意思
-
在 leetcode.com 的一个练习中,在 main 函数中创建了一棵二叉树,大概是一个解决方案文件。目标是创建一个函数,该函数将返回一个重新排列、排序的树头节点。这些节点大概是在调用我的函数之前创建的,因此已经为它们分配了内存。
标签: c pointers struct null-pointer