变量的值根据向量值而变化
问题描述:
我通过函数MontaVetorVerticalOtimizado(x, y, Vetor)
的参数发送数组int Vetor[33];
,在该数组填充之后,问题是在填充数组之后,函数OtimizaVerticalDentina()
的所有变量都用值数组,这似乎令人困惑,所以我加的图像,同时调试使其更容易理解:变量的值根据向量值而变化
第一功能:
void OtimizaVerticalDentina() {
int Vetor[33];
int x, y;
for (x = 1; x < NewImage.SizeX() - 1; x++)
{
for (y = 10; y < NewImage.SizeY() - 10; y++)
{
MontaVetorVerticalOtimizado(x, y, Vetor);
VerificaIntensidadeVetorVerticalOtimizado(Vetor);
if (bPreenche) {
NewImage.DrawPixel(x, y, 255, 255, 255);
} else {
NewImage.DrawPixel(x, y, 0, 0, 0);
bPreenche = true;
}
}
}
}
二级功能:
void MontaVetorVerticalOtimizado(int Px, int Py, int Vetor[33])
{
int x, y;
int i = 0;
unsigned char r, g, b;
for(x = Px - 1; x <= Px + 1; x++)
{
for(y = Py - 10; y <= Py + 10; y++)
{
NewImage.ReadPixel(x, y, r, g, b);
Vetor[i] = r;
i++;
}
}
}
注:
ImageClass NewImage; // global
*我在第一个测试方法中创建了其他变量,它们也发生了变化,有没有人知道可能发生了什么?
答
我能找到的唯一解释是你有一个缓冲区溢出。那就是你正在写这个数组(Vetor
),这个数组不够大,而且恰好覆盖了这个进程中不相关的内存。在这种情况下,您将覆盖调用函数的变量x
和y
的值。
我演示here:
#include <iostream>
void bar(int* arr)
{
for (int i = 0; i <= 35; i++) arr[i] = 255;
}
void foo()
{
int arr[33];
int x;
for (x = 0; x < 5; x++)
{
std::cout << x << '\n';
bar(arr);
std::cout << x << '\n';
}
}
int main()
{
foo();
return 0;
}
这将产生:0 255,并立即终止,因为循环变量得到了覆盖,随后x < 5
检查失败。你必须增加数组的大小(如果结果太小),或者确保你在其范围内索引。
哪个编译器?你是否添加了打印语句来确认(以防调试器对你说谎)? – Borgleader
啊,我的眼睛,太白了! – Stargateur
@Borgleader GNU GCC编译器,我在填充数组之前和之后在控制台上输出变量的值,并显示编译器没有说谎。 –