2017-09-23 201 views
-3

这里是我的代码。一种使用结构,另一种使用结构指针。但是当我不使用指针时,它不起作用。虽然我认为他们是一样的。但我仍然是初学者。所以我需要了解发生了什么问题。指针指向结构指针错误

不工作代码:

struct Node{ 
    int data; 
    struct Node* next; 
}; 

void insert(struct Node** head_ref,int data){ 
    //Not Working Here. The Header should change after every insert but it isn't Moving from it's Memory; 

    struct Node temp ; 

    temp.data = data; 
    temp.next = (*head_ref); 
    (*head_ref) = &temp; 
} 

int main(){ 
    struct Node *head = NULL; 

    insert(&head,4); 
    insert(&head,2); 
    insert(&head,11); 
    insert(&head,9); 

      while(head->next !=0){ 
       std::cout << head->data <<" "; 
       head = head->next; 
      } 
    return 0; 
} 

工作代码:

struct Node{ 
    int data; 
    struct Node* next; 
}; 

void insert(struct Node** head_ref,int data){ 
    //The Problem is in This Line. Pointer to Structure is Working But only Structure isn't 
    struct Node* temp = (struct Node*) malloc(sizeof(struct Node)) ; 

    temp->data = data; 

    temp->next = (*head_ref); 
    (*head_ref) = temp; 
} 

int main(){ 
    struct Node *head = NULL; 

    insert(&head,4); 
    insert(&head,2); 
    insert(&head,11); 
    insert(&head,9); 

      while(head->next !=0){ 
       std::cout << head->data <<" "; 
       head = head->next; 
      } 
    return 0; 
} 
+0

您可能想要点亮两者之间的确切区别。它需要一段时间才能找到。 –

+2

不要在C++中使用'malloc'。 'new'几乎总是你所需要的。 'unique_ptr '更好。如果你不是为了教育目的而这样做的,不要编写你自己的容器实现;你永远不会符合标准库的质量。 'insert'应该是'Node :: insert'。如果你不打算使用'unique_ptr ',那么你必须在每次动态分配后手动清理。 – patatahooligan

+0

@MateenUlhaq - 为什么你删除了OP代码的大部分,而没有评论?现在没有什么东西可以接近[MCVE]了,发布的代码看起来可能是C,而不是C++。尽管OP标签,原始代码显然是C++。滚回来。 –

回答

3

随着代码struct Node temp ; ... (*head_ref) = &temp;,你存储在本地变量的地址。只要函数insert完成,存储在此变量中的对象的生命周期结束,并且在此时间之后访问指针是未定义的行为。

这与您的第二种情况不同,其中struct Node* temp = (struct Node*) malloc(sizeof(struct Node))动态分配对象;这个对象的生命周期在它被明确删除时结束,这样你就可以引用它的地址。

+0

谢谢,我现在得到了概念。解决了我的问题。 –

0

它是堆之间和栈What and where are the stack and heap?

void insert(struct Node** head_ref,int data){ 
    //Not Working Here. The Header should change after every insert but it isn't Moving from it's Memory; 

    struct Node temp ; 

    temp.data = data; 
    temp.next = (*head_ref); 
    (*head_ref) = &temp; 
} 

的差在原始代码,温度位于stack,由于拿到范围

void insert(struct Node** head_ref,int data){ 
    //The Problem is in This Line. Pointer to Structure is Working But only Structure isn't 
    struct Node* temp = (struct Node*) malloc(sizeof(struct Node)) ; 

    temp->data = data; 

    temp->next = (*head_ref); 
    (*head_ref) = temp; 
} 

这结束时自动销毁可以工作,因为它位于heap,因此您必须在完成使用时手动删除它