我正在使用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 Y\n");
printf("Lab for Line and Point\n");
printf("number of lines >> \n");
scanf("%d",&numPoint); //comment this line for Line
pointValx[numPoint];
pointValy[numPoint];
printf("numPoint >> %d\n",numPoint);
for(int i = 0; i < numPoint;)
{
int x,y;
printf("Input for X >> %d\n", i);
scanf("%d",&x);
printf("numPoint >> %d\n",numPoint);
if(x >= 0 && x <= 400)
{
printf("Input for Y >> %d\n", i);
scanf("%d",&y);
if(y >= 0 && y <= 500)
{
pointValx[i] = x;
pointValy[i] = y;
i++;
}
else
{
printf("Y value crossed the limit\n");
}
}
else
{
printf("X value crossed the limit\n");
}
}
printf("End of Input file\n");
}
/// 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;
}
答案 0 :(得分:2)
pointValx[numPoint];
pointValy[numPoint];
此代码不能执行您认为的操作
它访问索引numPoint
的值,然后对其执行任何操作。访问值本身是未定义的行为。
你应该做的是将它们声明为指针,然后分配数组。
int* pointValx;
int* pointValy;
void takeInput()
{
printf("Screen Size is 0 - 400 in X and 0 - 500 in Y\n");
printf("Lab for Line and Point\n");
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);
答案 1 :(得分:1)
问题是这两个数组:
int pointValx[0];
int pointValy[0];
这里声明两个大小为零的数组。其中的任何索引都将超出界限并导致未定义的行为。
编译程序时修复了数组,以后不能在运行时更改大小。如果要在运行时更改大小,则需要使用std::vector
(我建议这样做)或使用指针和new[]
动态分配它们。