gpt4 book ai didi

c - 当函数的返回类型不允许我这样做时,如何在 C 中返回错误代码?

转载 作者:行者123 更新时间:2023-12-03 07:38:41 24 4
gpt4 key购买 nike

我知道标题不能 self 解释,但我无法用三言两语表达。无论如何,问题是我有一个 C 函数返回一个由 3 个整数组成的结构。这是它的定义。

typedef struct {
uint8_t r;
uint8_t g;
uint8_t b;
} Color;

这里是函数

Color PPMImage_getPixel(PPMImage *ppmImage, uint32_t x, uint32_t y) {
// FIXME: Check if (x, y) is in bounds.

return ppmImage->data[y * ppmImage->width + x];
}

现在,当特定条件失败时,我想返回一个错误值,告诉调用者函数遇到错误,但我不能,因为返回值是一个包含 3 个无符号整数的结构,我不能,因为例如,将每个字段设置为 -1 或返回 NULL 因为我没有返回指针。有没有优雅高效的方法来做到这一点?

最佳答案

将返回值的类型改为函数的err码,并传递一个指向要返回的struct color的指针

即:

int PPMImage_getPixel(PPMImage *ppmImage, uint32_t x, uint32_t y, Color * color)
{
// FIXME: Check if (x, y) is in bounds.
// TODO: validate color isn't null and valid, otherwise return -1

(*color) = ppmImage->data[y * ppmImage->width + x];
return 0;
}

关于c - 当函数的返回类型不允许我这样做时,如何在 C 中返回错误代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63474154/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com