<分区>
我正在编写一个程序,该程序应在 640x480 窗口中的随机位置创建随机大小的绿色框。运行以下代码时出现段错误。问题在于两个“for”循环。段错误通常发生在带有 startx 的嵌套“for”循环中。我怀疑缓冲区溢出,但不知道如何减少代码的体积。
//Globals
int width, height;
int endx, endy, starty, startx, randEnd, randStartX, randStartY;
unsigned char *pixmap;
void setPixels(){
for (int j = 1; j<100; j++) { // j == j-1 # of boxes
randStartX = rand() % width; // random # btw 0 and width
randStartY = rand() % height; // random # btw 0 and height
randEnd = 1 + (rand() % 100); // random # btw 0 - 100, not allowing box > 100.
startx = randStartX;
starty = randStartY;
endx = startx + randEnd;
endy = starty + randEnd;
for(int y = starty; y < endy; y++) { // first y coordinate of box
for(int x = startx; x < endx; x++) { // first x coordinate of box
cout << "endx = " << endx << endl;
int i = (y * width + x) * 3; // movement upwards for each pixel
pixmap[i++] = 0x00; //Increments i by one to move to the next part of pixel.
pixmap[i++] = 0xFF;
pixmap[i] = 0x00;
}
}
}
}
int main(int argc, char *argv[])
{
//initialize the global variables
srand (time(0));
width = 640;
height = 480;
pixmap = new unsigned char[width * height * 3];
setPixels(); // write code like ./pr01 red, etc.
glutInit(&argc, argv);
glutInitWindowPosition(100, 100); // Where the window will display on-screen.
glutInitWindowSize(width, height);
glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE);
glutCreateWindow("Assignment 01");
init();
glutReshapeFunc(windowResize);
glutDisplayFunc(windowDisplay);
glutMouseFunc(handleButton);
glutMainLoop();
return 0;
}
知道是什么原因造成的吗?这里有明显的逻辑问题吗?提前致谢。