繁体   English   中英

返回值时C代码混乱

[英]Confusion in the C code on returning a value

我编写了一个函数,该函数具有使用typedef创建的ListEntry的返回类型,如下所示

ListEntry RetrieveList(Position p,List *list)
{   if(p<0 || p>=list->count)
   {    Error("Invalid Position");
    return;
   }
else{
    SetPosition(p,list);
    ListEntry x=list->current->entry;
    return x;
  }
}

它检查位置是否有效。 如果位置无效,我不想从函数返回任何信息。 请帮忙 !

定义的RetrieveList()函数必须返回ListEntry值。 在不更改功能签名的情况下,一种可能性是选择一个可以指示无效位置条件的返回值。 由于ListEntryinttypedef ,根据OP注释,可以选择一个不能表示ListEntry的整数值; 也许-1

ListEntry RetrieveList(Position p, List *list)
{   if (p<0 || p >= list->count) {
        Error("Invalid Position");
        return -1;
    } else {
        SetPosition(p, list);
        ListEntry x = list->current->entry;
        return x;
    }
}

另外,您可以更改RetrieveList()的函数签名以返回指向ListEntry的指针。 然后,如果位置条件无效,则可以返回空指针。 但是,要进行此工作,您需要有一个ListEntry对象,以使返回的指针指向该对象。 这不能在RetrieveList()本地定义,因为此类局部变量的生存期在函数返回后结束(使指向它们的指针无效)。 可以使用malloc()分配ListEntry对象,但是稍后需要将该对象释放:

ListEntry * RetrieveList(Position p, List *list)
{   if (p<0 || p >= list->count) {
        Error("Invalid Position");
        return NULL;
    } else {
        SetPosition(p, list);

        /* allocate a ListEntry object, but must remember to free() */
        ListEntry *x = malloc(sizeof *x);

        /* should also check that allocation was successful before using */
        *x = list->current->entry;

        return x;
    }
}

上面的代码还应该检查从malloc()返回的值,以确保分配成功。 除了使用malloc() ,您还可以将指针传递给调用函数中定义的ListEntry对象。 无需记住使用这种方法对任何东西进行free() ,但看起来很笨拙:

ListEntry * RetrieveList(Position p, List *list, ListEntry *lent)
{   if (p<0 || p >= list->count) {
        Error("Invalid Position");
        lent = NULL;
    } else {
        SetPosition(p, list);
        *lent = list->current->entry;
    }

    return lent;
}

这将被称为:

ListEntry lentry;
if (RetrieveList(pos, list_ptr, &lentry) == NULL) {
    /* Handle invalid position */
} else {
    /* Proceed; lentry holds the value from list->current->entry */
}

我可能会选择第一个选项,因为那是最直接的。 另外,考虑删除typedef ,因为它们只会混淆代码。 除非有充分的理由隐藏此信息,否则最好了解正在使用的类型。

我已经使用指针完成如下

ListEntry *RetrieveList(Position p,List *list)
{   if(p<0 || p>=list->count)
{    Error("Invalid Position");
    return NULL;
}
else{
    SetPosition(p,list);
    ListEntry y=list->current->entry;
    ListEntry *x=&y;
    return x;
}
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM