如何 return 来自动态创建结构的函数的错误代码

How to return a error code from a function which creates structures dynamically

I return 来自 create_node 函数的错误代码,因此如果内存不可用,它 returns 到 main 并且程序结束。我得到一个整数与指针比较的错误。你能帮我处理一下吗?我是初学者。谢谢


node *create_node(void)
{
    node *newnode = (node *)malloc(sizeof(node));

    if (newnode == NULL)
        return 1;
    newnode->right = NULL;
    newnode->left = NULL;
    return newnode;
}
int main(void)
{
    int ret_val = 0;
    node *root = create_node();

    if (root == 1) {
        printf("Memory not available to create a node\n");
        return 0;
    }
    root->left = create_node();
    if (root->left == 1) {
        printf("Memory not available to create a node\n");
        return 0;
    }
    root->right = create_node();
    if (root->right == 1) {
        printf("Memory not available to create a node\n");
        return 0;
    }
}
 node *root = create_node();
 if(root == 1)

root 是指向 node 的指针,您将其与 1int 值进行比较。这就是为什么会出现整数与指针比较错误的原因。

在 C 语言中不允许将指针与 int 进行比较。至少如果您没有将 int 转换为指针类型则不允许。


解决方案:

如果 create_node() 中的分配失败,您应该 return 一个 NULL 指针而不是 returning 1:

 node *newnode = malloc(sizeof(*newnode));

 if (newnode == NULL)
 {
     return NULL;
 }

然后检查 rootmain() 中是否有 NULL:

 node *root = create_node();

 if (root == NULL)
 {
     fprintf(stderr,"Memory not available to create a node\n");
     return 1;
 }

旁注:

  1. 当发生错误时,main()的return值应为非零(1是常见的)。
  2. 您不需要转换 malloc() 的结果。这是一个link:Do I cast the result of malloc
  3. malloc(sizeof(*newnode)) - 使用它确保分配的 space 将始终适合指针 newnode 指向的对象(如果您稍后想要更改指向的结构,则很重要newnode).

根据 C 标准(6.5.9 相等运算符),相对于指针和整数的比较,有这样写的

2 One of the following shall hold:

— both operands have arithmetic type;

— both operands are pointers to qualified or unqualified versions of compatible types;

— one operand is a pointer to an object type and the other is a pointer to a qualified or unqualified version of void; or

— one operand is a pointer and the other is a null pointer constant.

所以你不能在不强制转换的情况下比较指针和整数。

但是在任何情况下都不需要 return 整数以防内存分配失败。在这种情况下,return NULL 就足够了。

所以函数看起来像

node * create_node(void)
{
    node *newnode = malloc( sizeof( node ) );

    if  ( newnode != NULL )
    {
        newnode->right = NULL;
        newnode->left  = NULL;
    }

    return newnode;
}

因此在main中你可以这样写

node *root = create_node();

if ( root == NULL ) {
    printf("Memory not available to create a node\n");
    return 0;
}

没有得到编译器的错误信息。