c - 在代码中没有明显除法的情况下除以零故障
问题描述
下面的代码来源于这里的一个问题。(我知道代码有几个逻辑问题,但我不明白它们是如何导致这个问题的。)
编辑: 我在 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;
}
解决方案
由于数组索引,除以 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__
是否不支持。
推荐阅读
- javascript - Datatables 插件返回此错误 SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
- continuous-integration - 使用 ssh 密钥推送到 gitlab CI 中的多个 github 存储库
- typescript - 多级索引类型打字稿
- matlab - 在 Matlab 中向 OFDMA 系统添加噪声
- javascript - Ag grid node.setSelected(true) 不在 UI 上显示选中的复选框
- swift - Xcode 11:iOS 13 在单元测试时特别不再触发`viewDidAppear`
- vim - Vim + elm-vim 无法识别 .elm 文件
- javascript - 如何在 React js 中为我的数组中的项目分配一个键?
- amazon-web-services - 同一区域内的 AWS 数据传输成本,但属于不同的账户?
- firebase - Firestore 使用 .hasAny() 规则限制字段