无法弄清楚为什么在CS50(第5周)的讲座示例中将节点指针分配为NULL。

huangapple go评论54阅读模式
英文:

Can't figure out why node pointer was assigned NULL on a lecture example from CS50 (Week 5)

问题

以下是代码的翻译部分:

所以以下的代码在讲座中被呈现,我不太理解为什么需要设置 n->next = null。David(讲师)说这样做会清理掉潜在的垃圾,但是垃圾最终不是应该被替换掉吗?

int main(int argc, char *argv[])
{
    // 存储数字的内存
    node *list = NULL;

    // 对于每个命令行参数
    for (int i = 1; i < argc; i++)
    {
        // 将参数转换为整数
        int number = atoi(argv[i]);

        // 为数字分配节点
        node *n = malloc(sizeof(node));
        if (n == NULL)
        {
            return 1;
        }
        n->number = number;
        n->next = NULL;

        // 将节点添加到列表前面
        n->next = list;
        list = n;
    }
}

因为它已经跟随着一个新的赋值 n->next = list。
在循环的第一次运行中,list 指向 null,之后它将指向更新后的值。垃圾最终会被替换掉,所以设置 n->next = null 似乎没有做任何事情?最终的节点将具有 NULL 指针,并且后续的节点会按顺序指向它们。
所以这可能是为了理解?或者它是否具有重要性,如果有的话,是什么重要性?

英文:

So the following code was presented in the lecture, and I'm struggling to understand why it was necessary to set n->next = null. David (Lecturer) did say it would be important to clean up potential garbage, but shouldn't the garbage end up being substituted anyway?

int main(int argc, char *argv[])
{
    // Memory for numbers
    node *list = NULL;

    // For each command-line argument
    for (int i = 1; i &lt; argc; i++)
    {
        // Convert argument to int
        int number = atoi(argv[i]);

        // Allocate node for number
        node *n = malloc(sizeof(node));
        if (n == NULL)
        {
            return 1;
        }
        n-&gt;number = number;
        n-&gt;next = NULL;

        // Prepend node to list
        n-&gt;next = list;
        list = n;
    }

Since it's already followed with a new assignment of n->next = list.
For the first run in the loop, list is pointing to null, and afterwards, it would point to the updated value. Garbage would be substituted anyway, so it doesn't seem like setting n->next = null is doing anything? The final node would have a NULL pointer and following nodes would be pointed in sequence.
So is it possibly for comprehension? Or does it have significance, and what would it be??

答案1

得分: 1

n->next = NULL; is not needed as the next line n->next = list; overwrites n->next.

Example is too trivial (or inaccurate) to demo the Lecturer's "important to clean up potential garbage" valid concern.

英文:

n-&gt;next = NULL; is not needed as the next line n-&gt;next = list; overwrites n-&gt;next.

Example is too trivial (or inaccurate) to demo the Lecturer's "important to clean up potential garbage" valid concern.

huangapple
  • 本文由 发表于 2023年6月22日 08:31:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76527946.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定