gpt4 book ai didi

c++ - 变量值在没有调用 scanf 的情况下发生变化

转载 作者:行者123 更新时间:2023-11-30 02:35:25 25 4
gpt4 key购买 nike

我在 C++ 中使用 openGL,当我在循环中获取顶点输入时,我遇到了一个问题,即顶点数量随着输入值的输入而变化,尽管我没有交换变量。

这里我遇到麻烦的变量是 numPoints,我在顶部用包含行声明了它(试图让它成为全局变量,我最初来自 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;
}

最佳答案

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);

关于c++ - 变量值在没有调用 scanf 的情况下发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33627987/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com