尝试使用采用结构并设置值的函数创建链表

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) [=10=] = {
  value = 1
  next = 0x0000000000000000
}

请注意,cur->next 在第一次迭代时已经是 NULL! 这意味着在 cur = cur->next 之后,cur 必须为 NULL,并且 cur->next 将取消引用空指针。

根本原因当然是你的赋值 cur = head1,它将你的 1->3->5->7->9->NULL 链表重新指向 1->NULL