为什么我需要转换从函数返回的结构?

时间:2011-11-03 17:47:19

标签: c

在一个文件中我有这个:

#include <stdio.h>
#include <stdlib.h>

static struct node* mynode;

struct node*
example(void)
{
    mynode = malloc(sizeof(struct node));
    ...fill up the struct here...
    return mynode;
}

调用例程是:

#include <stdio.h>
#include <stdlib.h>

int
main(void)
{
    mynode=example();
}

节点本身是在我未在此处显示的defs.h文件中定义的。 使用gcc编译时得到的警告是“赋值在调用例程中使得指针来自整数而不是强制转换”。

更改为mynode =(struct node *)example();删除该警告。该例程在任何情况下都有效,但我不明白为什么我会收到警告。

2 个答案:

答案 0 :(得分:4)

可能是你没有为struct node* example(void)声明原型而编译器认为它返回int吗?

答案 1 :(得分:2)

在调用example的文件中,example的返回类型未知,因此假定返回一个int,您将其分配给struct node *。因此警告。

你应该在调用文件中声明example的原型(在调用函数之前键入struct node* example(void);)或者(更好)创建一个名为example.h的头文件,其中你键入原型,然后在调用文件中包含头文件(即,键入#include "example.h" at the top). The header file thus defines the interface of the file where example`,使用这些函数的文件可以包含头文件,从而确保所有类型匹配,并删除任何编译器警告。