如果我使用此功能,我的控制台崩溃

My console crash if i use this function

本文关键字:我的 控制台 崩溃 功能 如果      更新时间:2023-10-16

我正在创建可以绘制到控制台但我的控制台崩溃的应用程序我测试了我的抽奖代码,它可以正常工作。(我在CodeBlocks中创建它(

如果我尝试运行功能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;
}

问题是您在rect()中的索引。

对于rect(2, 2, 3, 5)xp-xs-1yp-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;
  }
}

在线演示