当你有一个指针从一个指针结构指向另一个已经分配了内存的结构时,函数调用后会发生什么?我问一个问题提早了结构,导致我问这个问题: scope of struct pointers in functions函数调用后指针会发生什么变化
例如:
struct example{
//variables and pointers
struct clip *next;
}*Head
,然后我有数据类型结构的函数指针:
struct example *newNode=malloc(sizeof(struct example));
并且在相同的功能中,我将第一个节点(头部)链接到第二个节点(新节点):
Head->next=newNode;
函数退出后链接/指针是否仍然保留?我不确定这是否有意义,但是当您在链表末尾添加一个新节点时,必须首先浏览链表以查看链表的结束位置(下一个指针= NULL)。
例如:
void insert_at_end(){
//We have a pointer cp that goes through the linked list, initially cp->next points to `null so we create a newnode right away`
//struct example cp and newnode gets malloc'd here
if(Head != NULL){
cp=Head;
while(cp->next !=NULL){
cp=cp->next;
}
cp->next=newNode;
else{
//We link the head to the newNode `because we don't want to change the head for each new node added.`
head=newNode;
}
}
但每个newNode后,在列表的末尾添加我们退出的功能,所以会发生什么,当我们再次进入功能和经过链表,看看它结束了?它如何知道cp-> next指向什么?
代码时,所有的警告和调试信息编译(如:'GCC -Wall -g'在Linux上),并逐步与调试器('在Linux上gdb'),显示相关的指针,找出。在黑板上写下正在发生的事情。阅读几本很好的C编程书籍。你需要了解堆是什么,以及'malloc'和'free'在做什么。 – 2013-03-21 06:28:52
不是很有帮助。我知道我的问题可能不是最好的措辞,但本质上我是问这个问题,因为我不知道函数退出后指针会发生什么,所以不能绘出它。特别是当cp-> next指向下一个节点的内存位置时,它是否在函数存在后以某种方式保存?否则,我们还有什么可以通过链表? – user2122810 2013-03-21 06:32:48