英文:
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 < 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->number = number;
n->next = NULL;
// Prepend node to list
n->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->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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论