首页 > 解决方案 > 在代码中没有明显除法的情况下除以零故障

问题描述

下面的代码来源于这里的一个问题。(我知道代码有几个逻辑问题,但我不明白它们是如何导致这个问题的。)

编辑: 我在 Windows 上使用 CLANG,编译时显示常见警告。

它在指示的行(for 循环中的第一条语句)生成除以零错误,但没有明显的除数。谁能提供一些关于为什么会发生此错误的见解?

编辑 2:根据评论:将sepia函数中的第三个参数从

void sepia(int height, int width, RGBTRIPLE image[height][width])

void sepia(int height, int width, RGBTRIPLE image[3][4])

消除除以零错误。为什么?

typedef struct {
    double rgbtRed;
    double rgbtGreen;
    double rgbtBlue;
}RGBTRIPLE;

RGBTRIPLE image[3][4];

void sepia(int height, int width, RGBTRIPLE image[height][width])
{
    double sepiaRed = 0.0;
    double sepiaGreen = 0.0;
    double sepiaBlue = 0.0;
    // over height
    for (int h = 0; h < height; h++)
    {
        // over width
        for ( int w = 0; w < width; w++)
        {
            sepiaRed = .393 *  image[h][w].rgbtRed + .769 *  image[h][w].rgbtGreen + .189 *  image[h][w].rgbtBlue;
                           //  ^ Divide by zero occurs on this line.
            sepiaGreen = .349 *  image[h][w].rgbtRed + .686 *  image[h][w].rgbtGreen + .168 *  image[h][w].rgbtBlue;
            sepiaBlue = .272 *  image[h][w].rgbtRed + .534 *  image[h][w].rgbtGreen + .131 *  image[h][w].rgbtBlue;
            // space
            if (sepiaRed > 255 || sepiaGreen > 255 || sepiaBlue > 255)
            {
                sepiaRed = 255;
                sepiaGreen = 255;
                sepiaBlue = 255;
            }

            image[h][w].rgbtRed = (sepiaRed);
            image[h][w].rgbtBlue = (sepiaBlue);
            image[h][w].rgbtGreen = (sepiaGreen);
        }
    }
   return;
}

int main()
{
    sepia(3, 4, image);

    return 0;
}

标签: cdivide-by-zero

解决方案


由于数组索引,除以 0。

VLA支持故障或不存在。

//                         VLA prototype         v-------------v           
void sepia(int height, int width, RGBTRIPLE image[height][width]) {
        //                      v----v
        sepiaRed = .393 *  image[h][w].rgbtRed + .769 *  ...

代码可以使用如下非 VLA 方法,

void sepia(int height, int width, RGBTRIPLE image[3][4]) {

VLA 支持从 C99 开始。

对于 C11 或更高版本,请检查 __STDC_NO_VLA__是否不支持。


推荐阅读