首页 > 解决方案 > 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* 那么如何..?知道为什么会这样吗?

标签: cvisual-studio-code

解决方案


在使用函数时没有给出声明或定义InsertAtbeginning,因此编译器假设它返回int.

在您使用它修复的位置之前添加声明或移动定义。

另请注意,该行

    struct node* temp = (struct node*) malloc(sizeof(struct node*));

是错误的,因为

它应该是:

    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
}

推荐阅读