【发布时间】:2019-11-27 12:24:29
【问题描述】:
我目前正在阅读this question,它显示了有关使用void ** 作为参数从函数返回指针的问题。
我的代码主要将状态代码作为返回值,现在我正在寻找其他方法来返回这些指针和状态代码。所以我目前看到了几个选择,但没有一个真的让我开心。可能是我想多了。
// Output status through return value and the pointer through parameter
// - seems to be problematic because it requires casting to void **, which is invalid
int myfunc(void **output);
// Output status through return value, pointer through struct
// - seems to add unnecessary complexity to the interface
struct some_output { void *value };
int myfunc(struct some_output *output);
// Output pointer through return value, status through parameter
// - breaks consistency with other interfaces which always return the status code
void *myfunc(int *status);
现在我想知道是否还有其他替代的、优雅的方法可以从我没有想到的没有“缺点”的函数返回指针和状态码?
【问题讨论】:
-
为什么不返回一个结构体?
-
您可以返回一个结构,但我认为大多数 C 程序员不会喜欢这个,所以您的第一个解决方案是恕我直言最不意外的解决方案。
-
@Mat 谢谢!那是另一种选择...但是,它仍然以某种方式破坏了与始终返回状态代码的其余界面的一致性:-(
-
没有任何理由使用
void**。命名一个。如果你的函数内部使用动态分配,则返回通过type**分配的类型。 -
“可能我想多了。”不,它反过来。除了“这不仅仅是成功/失败”之外,帖子缺少
status的定义。它可能是一个 3 值int、一个字符串、一个结构,... 优雅 解决方案需要更多关于您尝试做什么的详细信息。按原样 - 这是未定义的。我们可以花费大量的 cmets(到目前为止 15 个)来梳理这些信息。相反,请考虑删除该帖子,然后再对编码目标进行更清晰的解释。