如何解决从“结构节点*”类型分配给“结构节点”类型时,C不兼容的类型
我只写了函数,当我编译它时,总是会出现这些错误。
我知道问题出在queue->arr[queue->rear]=item
中。但是我已经在queue->arr
中将Node*
定义为Queue
,为什么代码仍然是错误的?
[Error] incompatible types when assigning to type 'struct Node' from type 'struct Node *'
[Error] incompatible type for argument 1 of 'insertValue'
[Note] expected 'struct Node *' but argument is of type 'struct Node'
struct Node {
int data;
struct Node* left;
struct Node* right;
};
struct Queue{
int rear;
int front;
int size;
int capacity;
struct Node* arr;
};
struct Node* newNode(int item){
struct Node* node=(struct Node*) malloc(sizeof(struct Node));
node->left= NULL;
node->right=NULL;
node->data= item;
return node;
}
struct Queue* creatQ()
{
struct Queue* queue= (struct Queue*)malloc(sizeof(struct Queue*));
queue->rear=0;
queue->front=0;
queue->size=0;
queue->capacity= MAXQUEUE;
queue->arr=(struct Node*)malloc(queue->capacity*sizeof(struct Node));;
return queue;
}
void push(struct Queue* queue,struct Node* item)
{
if(queue->rear==(MAXQUEUE-1)){
printf("Queue full\n");
}
else{
queue->rear= (queue->rear+1)%queue->capacity;
queue->arr[queue->rear]=item;
queue->size++;
}
}
struct Node pop(struct Queue* queue)
{
struct Node item;
if (queue->size==0){
printf("Empty queue\n");
}
else{
item=queue->arr[queue->front];
queue->front= (queue->front+1)%queue->capacity;
queue->size--;
return item;
}
}
struct Node front(struct Queue* queue)
{
struct Node item;
if(queue->size!=0){
item=queue->arr[queue->front];
return item;
}
}
struct Node* insertValue(struct Node* root,int value,struct Queue* queue)
{
struct Node* node= newNode(value);
struct Node item= front(queue);
if (root==NULL){
root=node;
}
else if(item.left==NULL){
item.left=node;
}
else {
item.right=node;
pop(queue);
}
push(queue,node);
return root;
}
解决方法
有很多错误。例如在此声明中
struct Queue* queue= (struct Queue*)malloc(sizeof(struct Queue*));
^^^^^^^^^^^^^
使用了错误的malloc调用参数。你需要写
struct Queue* queue= (struct Queue*)malloc(sizeof(struct Queue));
^^^^^^^^^^^^
或者在函数push
中存在错误的分配
queue->arr[queue->rear]=item;
变量item
的类型为struct Node *
void push(struct Queue* queue,struct Node* item)
^^^^^^^^^^^^^^^^^
而指针arr
所指向的数组的元素类型为struct Node
。
如果数据成员大小等于0,则函数front
不返回任何内容。
struct Node front(struct Queue* queue)
{
struct Node item;
if(queue->size!=0){
item=queue->arr[queue->front];
return item;
}
}
或者此错误消息
[Error] incompatible type for argument 1 of 'insertValue'
[Note] expected 'struct Node *' but argument is of type 'struct Node'
表示在某个地方您正在调用向函数传递struct Node
类型的对象,而相应的参数具有struct Node *
类型。
struct Node* insertValue(struct Node* root,int value,struct Queue* queue)
^^^^^^^^^^^^^^^^^
在编写任何新函数之前,请使用先前定义的函数编译程序。如果不确定已编写的代码是否有效,请不要编写新代码。
请注意,如果将队列实现为数组,则将数组元素定义为具有数据成员left
和right
并没有太大意义。
struct Node {
int data;
struct Node* left;
struct Node* right;
};
新元素被添加到数组的当前尾部,并从其头部弹出。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。