下面的代码是由一个问题衍生出来的 此处. (我知道这段代码存在几个逻辑问题,但我不明白它们是如何造成这个问题的)。
编辑:我在Windows上使用CLANG,编译时显示普通警告。 我在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__
因不支持。