C 当函数的返回类型不为';你不允许我那样做吗?
我知道这个标题不是自我解释的,但我不能用几句话来表达。 无论如何,问题是我有一个C函数,它返回一个由3个整数组成的结构。这里是它的定义C 当函数的返回类型不为';你不允许我那样做吗?,c,function,error-handling,return,C,Function,Error Handling,Return,我知道这个标题不是自我解释的,但我不能用几句话来表达。 无论如何,问题是我有一个C函数,它返回一个由3个整数组成的结构。这里是它的定义 typedef结构{ uint8_t r; uint8_t g; uint8_t b; }色彩; 这就是函数 Color PPMImage\u getPixel(PPMImage*PPMImage,uint32\u t x,uint32\u t y){ //修正:检查(x,y)是否在边界内。 返回ppmImage->data[y*ppmImage->width
typedef结构{
uint8_t r;
uint8_t g;
uint8_t b;
}色彩;
这就是函数
Color PPMImage\u getPixel(PPMImage*PPMImage,uint32\u t x,uint32\u t y){
//修正:检查(x,y)是否在边界内。
返回ppmImage->data[y*ppmImage->width+x];
}
现在,当一个特定条件失败时,我想返回一个错误值,告诉调用方函数遇到错误,但我不能,因为返回值是一个具有3个无符号整数的结构,并且我不能,例如,将每个字段设置为-1或返回NULL,因为我没有返回指针。有没有一种优雅而有效的方法可以做到这一点?将返回值的类型更改为函数的错误代码,并传递一个要返回的结构颜色指针 即:
我希望有一个指向缓冲区的指针作为函数的输入参数,并返回一个
int
int PPMImage_getPixel(Color* p_color, PPMImage *ppmImage,
uint32_t x, uint32_t y)
{
if (some error)
{
return 0;
}
// Copy the struct into buffer
memcpy(p_color, &ppmImage->data[y * ppmImage->width + x], sizeof (Color));
return 1;
}
假设某个未定义的结构,但可以更改它。创建这个是为了有一些可以编译的东西
typedef struct PPMImage
{
uint8_t width;
Color data[10];
} PPMImage;
在main()
中创建缓冲区,并将该缓冲区的地址作为输入
int main(void)
{
PPMImage image;
Color color_buf;
uint32_t x = 5, y = 3;
if (!PPMImage_getPixel(&color_buf, &image, x, y))
{
printf("ERROR PPMImage_getPixel()\n");
exit(0);
}
printf("PPMImage_getPixel() returned no error.\n");
return 0;
}
一种方法是将结果分配给输出参数并返回错误代码,如下所示:
int PPMImage_getPixel(PPMImage *ppmImage, uint32_t x, uint32_t y, Color *result);
但是,由于我是命令-查询分离的粉丝,我也会将错误代码分配给输出参数:
void PPMImage_getPixel(PPMImage *ppmImage, uint32_t x, uint32_t y, Color *result, int *error);
另一种方法是,如果x或y太大,通过返回最近的像素来定义不存在的错误:
Color PPMImage_getPixel(PPMImage *ppmImage, uint32_t x, uint32_t)
{
if (x < 0) {
x = 0;
} else if (x > xMax) {
x = xMax;
}
if (y < 0) {
y = 0;
} else if (y > yMax) {
y = yMax;
}
...
}
Color PPMImage\u getPixel(PPMImage*PPMImage,uint32\u t x,uint32\u t)
{
if(x<0){
x=0;
}如果(x>xMax),则为else{
x=xMax;
}
if(y<0){
y=0;
}如果(y>yMax),则为else{
y=yMax;
}
...
}
Color PPMImage_getPixel(PPMImage *ppmImage, uint32_t x, uint32_t)
{
if (x < 0) {
x = 0;
} else if (x > xMax) {
x = xMax;
}
if (y < 0) {
y = 0;
} else if (y > yMax) {
y = yMax;
}
...
}