我正在创建可以绘制到控制台的应用程序,但我的控制台崩溃了 我测试了我的绘图代码,它工作正常。 (我在代码块中创建了它)
如果我尝试运行函数
rect()
请帮助我不知道如何使其发挥作用。 (我用javascript编程(p5 * .js),这更容易)
#include <iostream>
#include <stdio.h>
#define WIDTH 80
#define HEIGHT 40
using namespace std;
//just including basic stuff please try to make solution without including more lib.
int grid[HEIGHT][WIDTH];
int x, y, xp, xs, yp, ys, n;
int length = HEIGHT * WIDTH;
void printarray()
{
//it will print array when it is called in to the console
for (y = 0; y < HEIGHT; y++)
{
for (x = 0; x < WIDTH; x++)
{
/*if (grid[y][x]%2 == 0){ //just test
printf("#");
}else{
printf("_");
}
}
printf("\n");
}
for (int n=0; n<WIDTH; ++n){
printf("=");
}
printf("\n");
}*/
if (grid[y][x] == 1)
{
//it just dicide if it draw # or _
printf("#");
}
else
{
printf("_");
}
}
printf("\n");
}
for (int n = 0; n < WIDTH; ++n)
{
printf("=");
}
printf("\n");
}
void rect(int xp, int yp, int xs, int ys)
{
//it should print rectangle
for (y = yp; y < yp + ys; y++)
{
//xp is position on x
grid[y][xp] = 1; //xs is how long is on x
grid[y][xp - xs] = 1; //every loop set 2 lines in array grid[][]
}
for (x = xp; x < xp + xs; x++)
{
grid[yp][x] = 1;
grid[yp - ys][x] = 1;
}
}
int main()
{ //main function
for (y = 0; y < HEIGHT; y++)
for (x = 0; x < WIDTH; x++)
{
//grid[y][x] = x+y*(WIDTH-1); //just part of test
grid[y][x] = 0;
rect(2, 2, 3, 5); //if i call this function my console crash or dont do anything
} //and it sometimes write in my build log Process terminated with status -1073741510
printarray();
return 0;
}
答案 0 :(得分:0)
问题是您在rect()
中的索引。
对于rect(2, 2, 3, 5)
,xp-xs
为-1
,yp-ys
也为-1
。因此grid[y][xp-xs]
和grid[yp-ys][x]
不受限制。所以它是UB,因此在某些情况下观察到的崩溃但并非总是如此。
你应该纠正循环:从zp到zs或从zp到zp + zs(取决于xs,ys是相反点的坐标,还是xs和ys是矩形的宽度)。例如:
void rect (int xp, int yp, int xs, int ys) {
for (y=yp; y<=yp+ys; y++) {
//xp is position on x
grid[y][xp]=1; //xs is how long is on x
grid[y][xp+xs]=1; //every loop set 2 lines in array grid[][]
}
for (x=xp; x<=xp+xs; x++) {
grid[yp][x]=1;
grid[yp+ys][x]=1;
}
}