了解古代C的动态分配[关闭]

问题描述 投票:-3回答:1
如果您不熟悉动态内存分配,则可以将其视为大脑的绕线者。

首先将此代码另存为您的bin目录中的C程序。

#include<stdio.h> #include<conio.h> struct node { int data; struct node *next; } *head=NULL; void ins_at_beg() { struct node *node=malloc(4); node->next=head; head=node; printf("Please enter the value to be inserted at the start: "); scanf("%d",node); // POINT A } void ins_at_end() { struct node *node=head; while(node->next) node=node->next; node->next=malloc(4); printf("Please enter the value to be inserted at the end: "); scanf("%d",node->next->data); // POINT B } void main() { clrscr(); ins_at_end(); printf("%d",head->data); getch(); }

执行此代码,一切都会看起来很好。

现在,在程序将主要功能的ins_at_end()执行到ins_at_beg()并执行程序之后,一切仍然看起来还不错。

现在

手动撤消上述更改(将ins_at_beg更改为ins_at_end)并执行程序。现在,您将head->data的值设为0。

现在只需将'Point A'的node更改为node->data,您将看到输入的值反映在屏幕上(注意:我们没有在主函数中调用该函数)

现在再次颠倒上述更改并获得0作为head->data的默认值。

这里要注意的主要事情是,输出将由一个刚刚定义的函数更改,而该函数在主函数中未调用。

玩一会儿,您就会知道我在说什么。

问题:

即使实际上没有调用在主函数中进行更改的函数,当我将node更改为node->data时,为什么程序仍能正常工作?
c turbo-c++
1个回答
2
投票
此:
© www.soinside.com 2019 - 2024. All rights reserved.