【问题标题】:assign an address to the Node* in link list?为链接列表中的节点*分配地址?
【发布时间】:2013-10-07 09:01:32
【问题描述】:
   this is the structure of my node
    typedef struct Node{
    int x;
    Node* Next;
  };

  // in main() i can make the head pointer,and assign it to NULL i-e 

     Node* start_pointer=NULL;  //this line is in my main() function
                            // and i consider it head pointer


   void add_node(Node* start_pointer){

Node first;
cout<<"Enter the value of X\n ";
cin>>first.x;
if (start_pointer==NULL){
    start_pointer=&first;   //try to assign an address of object of its pointer
    first.Next=NULL;
    }


else {                             

    Node* temp=start_pointer;
    while (temp->Next != NULL){         //program is break at this stage  
        temp=temp->Next;}

    temp->Next=first.Next;                
    first.Next=NULL;

}

我正在为 node* 分配一个地址并尝试使用 '->' 运算符来捕获它,可以吗? 每次我运行 add_node 函数时它都会执行,但不幸的是它没有进入 else 条件

【问题讨论】:

    标签: c++ pointers linked-list structure


    【解决方案1】:

    您的代码有两个不同的问题

    首先你必须在 add_node 中分配新节点,而不是获取局部变量的地址。

    不是这个

    start_pointer=&first;
    first.Next=NULL;
    

    你应该有这个

    start_pointer=new Node;
    start_pointer->Next=NULL;
    

    first 的地址是错误的,因为当你退出函数时first 会被破坏。所以 start_pointer 将指向一个已被销毁的对象,您的程序将崩溃。但是使用new 分配的对象会一直存在,直到您delete 他们为止。

    第二个错误是你的函数在add_node函数中改变了start_pointer。它不会更改 main 函数中的 start_pointer。这两个变量可能具有相同的名称,但它们是完全不同的变量。这就是为什么您的代码永远不会进入 add_node 的 else 部分的原因。要更改 main 中的 start_pointer,您需要通过在类型后添加 &amp; 来更改 add_node 函数以使用引用。

    void add_node(Node*& start_pointer){ // use a reference
    

    现在 add_node 中的 start_pointer 是 main 中 start_pointer 的引用,因此 add_node 中 start_pointer 的更改将影响 main 中的 start_pointer。

    【讨论】:

      【解决方案2】:

      这个函数:

      void add_node (Node* start_pointer) {
      
          Node first;
          ...
          start_pointer = &first;
          first.Next=NULL;
      }
      

      存储一个局部变量的地址(具有自动存储持续时间的对象),该地址仅在该函数执行期间存在。当执行超出范围时,first 被破坏并且您的指针变得无效~> 如果您尝试访问此指针,它将产生 未定义的行为。。 p>

      可能的解决方案可能是动态分配Node

      start_pointer = new Node();
      start_pointer->Next = NULL;
      

      只是不要忘记在某个时候调用delete 来释放此内存。

      【讨论】:

        猜你喜欢
        • 2023-03-06
        • 2013-12-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-19
        • 1970-01-01
        • 1970-01-01
        • 2012-06-20
        相关资源
        最近更新 更多