![](/img/trans.png)
[英]Trying to implement a function to delete a struct in a linked list while assigning the struct before it to point to the struct after it
[英]trying to create a linked list using a function that takes a struct and sets the value
#include <iostream>
using namespace std;
結構
struct intnode { int value;
struct intnode *next; };
typedef struct intnode IntNode;
用於創建新節點並設置新值的代碼
IntNode *intnode_construct(int value, IntNode *next) {
IntNode *p = (IntNode*)malloc(sizeof(IntNode));
assert (p != NULL);
p->value=value;
p->next = next;
return p;
}
int main(int argc, const char * argv[]){
IntNode *head1=NULL;
IntNode *head2=NULL;
IntNode *cur= NULL;
head1 = intnode_construct(1, cur);
值應該是 1,3,5,7
for(int i=1;i<10;(i=i+2))
{
cur = intnode_construct(i, cur);
}
cur=head1;
打印函數
一旦我運行程序,它就會給我一個運行時錯誤
do{
cout<<cur->value<<endl;
cur=cur->next;
}
while(cur->next != NULL);
return 0;
}
正如您所說的調試器無濟於事的說法相反,我在 do-while 循環的第一次迭代中放置了一個斷點。 觀察:
(lldb) b 38
Breakpoint 1: where = debuggerisnohelp`main + 126 at debuggerisnohelp.cpp:38:15, address = 0x0000000100000cae
(lldb) r
Process 4631 launched: '/tmp/debuggerisnohelp' (x86_64)
Process 4631 stopped
* thread #1, queue = 'com.apple.main-thread', stop reason = breakpoint 1.1
frame #0: 0x0000000100000cae debuggerisnohelp`main(argc=1, argv=0x00007ffeefbff708) at debuggerisnohelp.cpp:38:15
35 cur=head1;
36
37 do{
-> 38 cout<<cur->value<<endl;
39 cur=cur->next;
40 }
41 while(cur->next != NULL);
Target 0: (debuggerisnohelp) stopped.
(lldb) p *cur
(IntNode) $0 = {
value = 1
next = 0x0000000000000000
}
請注意, cur->next
在第一次迭代時就已經是NULL
了! 這意味着在cur = cur->next
, cur
必須為 NULL 並且cur->next
將取消引用一個空指針。
根本原因當然是你的賦值cur = head1
head1 ,它把你好的1->3->5->7->9->NULL
鏈表重新指向1->NULL
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.