这里是我的代码。一种使用结构,另一种使用结构指针。但是当我不使用指针时,它不起作用。虽然我认为他们是一样的。但我仍然是初学者。所以我需要了解发生了什么问题。指针指向结构指针错误
不工作代码:
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;
}
您可能想要点亮两者之间的确切区别。它需要一段时间才能找到。 –
不要在C++中使用'malloc'。 'new'几乎总是你所需要的。 'unique_ptr'更好。如果你不是为了教育目的而这样做的,不要编写你自己的容器实现;你永远不会符合标准库的质量。 'insert'应该是'Node :: insert'。如果你不打算使用'unique_ptr ',那么你必须在每次动态分配后手动清理。 –
patatahooligan
@MateenUlhaq - 为什么你删除了OP代码的大部分,而没有评论?现在没有什么东西可以接近[MCVE]了,发布的代码看起来可能是C,而不是C++。尽管OP标签,原始代码显然是C++。滚回来。 –