变量值在没有scanf调用的情况下正在更改
variable value is changing without scanf call
我在C++中使用openGL,当我为循环中的顶点输入时,我遇到了一个问题,即顶点数量随着输入值的输入而变化,尽管我没有交换变量。
这里我遇到麻烦的变量是numPoints,我在顶部用include行声明了它(为了使它全局化,我来自Java)。并且当输入循环值改变为i==2时,该值改变。我从键盘上取两个值,x和y。下面给出了主要函数的详细代码。
#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#include <stdlib.h>
#include "stdio.h"
int pointValx[0];
int pointValy[0];
int numPoint;
void takeInput()
{
printf("Screen Size is 0 - 400 in X and 0 - 500 in Yn");
printf("Lab for Line and Pointn");
printf("number of lines >> n");
scanf("%d",&numPoint); //comment this line for Line
pointValx[numPoint];
pointValy[numPoint];
printf("numPoint >> %dn",numPoint);
for(int i = 0; i < numPoint;)
{
int x,y;
printf("Input for X >> %dn", i);
scanf("%d",&x);
printf("numPoint >> %dn",numPoint);
if(x >= 0 && x <= 400)
{
printf("Input for Y >> %dn", i);
scanf("%d",&y);
if(y >= 0 && y <= 500)
{
pointValx[i] = x;
pointValy[i] = y;
i++;
}
else
{
printf("Y value crossed the limitn");
}
}
else
{
printf("X value crossed the limitn");
}
}
printf("End of Input filen");
}
/// MAIN FUNCTION
int main(int argc, char *argv[])
{
int win;
glutInit(&argc, argv); /* initialize GLUT system */
glutInitDisplayMode(GLUT_RGB);
glutInitWindowSize(400,500); /* width=400pixels height=500pixels */
win = glutCreateWindow("GL_LINES and Points"); /* create window */
/* from this point on the current window is win */
takeInput();
glClearColor(0.0,0.0,0.0,0.0); /* set background to black */
gluOrtho2D(0,400,0,500); /* how object is mapped to window */
glutDisplayFunc(displayCB); /* set window's display callback */
glutMainLoop(); /* start processing events... */
/* execution never reaches this point */
return 0;
}
pointValx[numPoint];
pointValy[numPoint];
这个代码不会做你认为它会做的事情
它访问索引numPoint
处的值,然后不对其执行任何操作。访问值本身是未定义的行为。
您应该做的是将它们声明为指针,然后分配数组。
int* pointValx;
int* pointValy;
void takeInput()
{
printf("Screen Size is 0 - 400 in X and 0 - 500 in Yn");
printf("Lab for Line and Pointn");
printf("number of lines >> n");
scanf("%d",&numPoint); //comment this line for Line
pointValx = (int*)malloc(numPoint*sizeof(int));
pointValy = (int*)malloc(numPoint*sizeof(int));
在你处理完它们之后,你应该释放它们:
free(pointValx);
free(pointValy);
问题在于这两个数组:
int pointValx[0];
int pointValy[0];
这里声明两个大小为零的数组。其中的任何索引都将超出范围,并导致未定义的行为。
数组在编译程序时是固定的,以后在运行时不能更改大小。如果您想在运行时更改大小,那么您需要使用std::vector
(这是我建议的),或者使用指针和new[]
动态分配它们。
相关文章:
- 如果 std::vector::clear() 不是静态的,如何在没有实例的情况下调用它?
- C++ - 如何在不调用其属性的情况下调用类?
- C++ 在不释放内存的情况下调用析构函数
- Python在不引用类名的情况下调用类函数
- 为什么在这种情况下调用非常量右值移动构造函数?
- 是否可以在没有显式专用化的情况下调用可变参数模板函数?
- 使用按引用调用时,不能在没有对象的情况下调用成员函数 const
- 您可以在不调用构造函数的情况下调用攻击器吗?
- 命名空间:不能在没有对象的情况下调用成员函数
- 哪些语言将在没有显式桥接的情况下调用C++
- 如何在不重新索引顶点的情况下调用"boost::remove_vertex"?
- C :在没有对象实例的情况下调用非静态成员函数
- 在不实例化的情况下调用不同派生类的虚拟方法
- C 如何在没有错误的情况下调用void函数
- 在MSVC上的数组初始化期间,destructor在不复制或移动构造方的情况下调用
- 在不指定实例化的情况下调用类模板的静态方法的方法
- 为什么INVOKE总是取消引用数据成员,而不是在可能的情况下调用
- 是否可以在不实例化派生类的情况下调用该类的虚拟函数
- 无法在没有对象的情况下调用成员函数(尽管我相信我确实初始化了它)
- 为什么在没有赋值运算符的情况下调用转换构造函数