*head' 是一个指针;您是要使用“->”吗?为什么我得到这个
*head' is a pointer; did you mean to use '->'? Why am I getting this
第 20 行出现错误。 20 | head->prev=temp;
我可以将 struct Node head 定义为全局指针,然后代码就可以工作了。但是为什么当我将它定义为 main() 中的局部变量时出现错误。我哪里错了?
谢谢!
#include<stdio.h>
#include<stdlib.h>
struct Node{
int data;
struct Node* next;
struct Node* prev;
};
void insert(struct Node** head,int x){
struct Node* temp=(struct Node*)malloc(sizeof(struct Node));
temp->data=x;
if(*head==NULL){
*head=temp;
return;
}
*head->prev=temp;
temp->next=*head;
*head=temp;
}
void print(struct Node* head){
struct Node* temp=head;
printf("List is: ");
while(temp!=NULL){
printf("%d",temp->data);
temp=temp->next;
}
}
void main(){
struct Node* head = NULL;
insert(&head,1);
insert(&head,2);
insert(&head,3);
insert(&head,4);
insert(&head,5);
print(head);
}
这一行:
*head->prev=temp;
->
运算符的优先级高于*
运算符,因此解析为:
*(head->prev)=temp;
这是无效的,因为 head
是指向结构指针的指针,而不是指向结构的指针。您需要添加括号以强制 *
运算符直接应用于 head
:
(*head)->prev=temp;
此外,不要强制转换 malloc
的 return 值,因为它会掩盖代码中的其他错误。
第 20 行出现错误。 20 | head->prev=temp; 我可以将 struct Node head 定义为全局指针,然后代码就可以工作了。但是为什么当我将它定义为 main() 中的局部变量时出现错误。我哪里错了? 谢谢!
#include<stdio.h>
#include<stdlib.h>
struct Node{
int data;
struct Node* next;
struct Node* prev;
};
void insert(struct Node** head,int x){
struct Node* temp=(struct Node*)malloc(sizeof(struct Node));
temp->data=x;
if(*head==NULL){
*head=temp;
return;
}
*head->prev=temp;
temp->next=*head;
*head=temp;
}
void print(struct Node* head){
struct Node* temp=head;
printf("List is: ");
while(temp!=NULL){
printf("%d",temp->data);
temp=temp->next;
}
}
void main(){
struct Node* head = NULL;
insert(&head,1);
insert(&head,2);
insert(&head,3);
insert(&head,4);
insert(&head,5);
print(head);
}
这一行:
*head->prev=temp;
->
运算符的优先级高于*
运算符,因此解析为:
*(head->prev)=temp;
这是无效的,因为 head
是指向结构指针的指针,而不是指向结构的指针。您需要添加括号以强制 *
运算符直接应用于 head
:
(*head)->prev=temp;
此外,不要强制转换 malloc
的 return 值,因为它会掩盖代码中的其他错误。