Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将malloc返回的结构类型转换为结构类型?_C - Fatal编程技术网

如何将malloc返回的结构类型转换为结构类型?

如何将malloc返回的结构类型转换为结构类型?,c,C,如何将malloc返回的类型转换地址转换为结构节点类型? 当我试图编译下面的代码时,每次关于类型的更改都会显示错误 struct node { int info; struct node *link; }; struct node createnode() { struct node *n; n = (struct node *) malloc( sizeof(struct node) ); // error: incompatible types whe

如何将malloc返回的类型转换地址转换为结构节点类型?
当我试图编译下面的代码时,每次关于类型的更改都会显示错误

struct node {
    int info;
    struct node *link;
};
struct node createnode() {
    struct node *n;
    n = (struct node *) malloc( sizeof(struct node) );
    // error: incompatible types when returning type 'struct node *' but 'struct node' was expected
    return n;
}

您的
createnode
函数返回
struct节点
,但您返回一个
struct节点*

您应该更改方法签名,使其返回一个
结构节点*

struct node createnode()
{ ...
表示函数返回一个
struct节点
,而不返回一个
struct节点*

struct node createnode()
{
struct node *n;
n=(struct node *)malloc(sizeof(struct node));
return(n);
}
请注意,
n
是一个
struct节点*
——指向
struct节点的指针

您在函数定义中省略了
*

struct node *createnode()
{
struct node *n;
n=malloc(sizeof(struct node));
return(n);
}

请注意,在C中,您不必强制转换
void
指针。事实上,如果您这样做,您可以隐藏潜在的问题。

您将函数声明为返回一个节点,但正在尝试返回一个节点*。您可能需要更改函数声明
struct node*createnode()…
struct node createnode()
更改为
struct node*createnode()


您正试图返回一个指向
节点的指针
,当您希望返回一个
节点

时,实际上错误在return语句中。函数的返回类型是
struct node
,而它应该是
struct node*
。看起来像是输入错误。@r3musn0x我实际上怀疑错误在函数的定义中,因为使用了
malloc()
@AndrewHenle,我的意思是编译错误在return语句中,而不是OP注释的行中。实际错误当然在返回类型中。谢谢您的帮助