c - struct* 赋值语句显示警告
问题描述
它是 C 中 Linkedlist 实现的代码,只有一个功能,即在列表的开头插入一个元素
#include<stdio.h>
struct node{
char data;
struct node* next;
};
int main()
{
struct node* head = NULL;
head = InsertAtbeginning(head,'g'); //C4047
head = InsertAtbeginning(head,'f'); //C4047
}
struct node* InsertAtBeginning(struct node* head, char key)
{
struct node* temp = (struct node*) malloc(sizeof(struct node*));
temp->data = key;
temp->next = head;
head = temp;
return head;
}
在 vscode 中编译时,我在注释行中收到警告
警告 C4047:“=”:“节点 *”与“int”的间接级别不同
如何!!?我没有返回任何 int 值。并且左右操作数都是相同类型的,即 struct node* 那么如何..?知道为什么会这样吗?
解决方案
在使用函数时没有给出声明或定义InsertAtbeginning
,因此编译器假设它返回int
.
在您使用它修复的位置之前添加声明或移动定义。
另请注意,该行
struct node* temp = (struct node*) malloc(sizeof(struct node*));
是错误的,因为
- 它只为一个指针分配空间,而您必须为结构分配空间。
malloc()
家庭铸造结果被认为是一种不好的做法。
它应该是:
struct node* temp = malloc(sizeof(*temp));
或者(如果你想坚持写类型名称sizeof
:
struct node* temp = malloc(sizeof(struct node));
固定代码(添加声明):
#include<stdio.h>
#include<stdlib.h>
struct node{
char data;
struct node* next;
};
struct node* InsertAtBeginning(struct node* head, char key); // declaration
int main()
{
struct node* head = NULL;
head = InsertAtbeginning(head,'g'); //C4047
head = InsertAtbeginning(head,'f'); //C4047
}
struct node* InsertAtBeginning(struct node* head, char key)
{
struct node* temp = malloc(sizeof(*temp));
temp->data = key;
temp->next = head;
head = temp;
return head;
}
固定代码(移动定义):
#include<stdio.h>
#include<stdlib.h>
struct node{
char data;
struct node* next;
};
struct node* InsertAtBeginning(struct node* head, char key)
{
struct node* temp = malloc(sizeof(*temp));
temp->data = key;
temp->next = head;
head = temp;
return head;
}
int main()
{
struct node* head = NULL;
head = InsertAtbeginning(head,'g'); //C4047
head = InsertAtbeginning(head,'f'); //C4047
}
推荐阅读
- scikit-learn - 为什么 Skealearn-NearestNeighbors 返回奇怪/错误的结果?
- mysql - 我需要知道是否有其他方法可以在没有 cmd 的情况下使用 sql 命令行
- flutter - 颤振:如何制作这样的容器边框?
- android - 如何获取从android中的布局操作中单击的项目的ID?
- react-native - 如何使用 react-native-maps 动态创建标记?
- javascript - 无法使用 React Native 将值从一个组件传递到另一个组件
- react-native - React Native UI Kitten 更改汉堡图标颜色和状态栏图标颜色
- azure - 了解 Azure Databricks 群集 Log4j 输出
- node.js - 如何在托盘中启动时隐藏电子应用程序
- python - 在一个中心位置全局修改请求