我在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[]
动态分配它们。