以下是我的两个代码。一个使用结构和另一个使用指针结构。但是,当我不使用指针时,它不起作用。虽然我认为它们是相同的。但我还是初学者。所以我需要了解出了什么问题。
不工作代码:
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 :(得分:3)
使用代码struct Node temp ; ... (*head_ref) = &temp;
,可以存储局部变量的地址。函数insert
完成后,存储在此变量中的对象的生命周期结束,并且在此时间之后访问指针是未定义的行为。
这与第二种情况不同,struct Node* temp = (struct Node*) malloc(sizeof(struct Node))
动态分配对象;这个对象的生命周期在明确删除时结束,这样你就可以引用它的地址了。
答案 1 :(得分: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;
}
在原始代码中,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
,因此您必须在使用完毕后手动将其删除