如果我使用此功能,我的控制台崩溃
My console crash if i use this function
我正在创建可以绘制到控制台但我的控制台崩溃的应用程序我测试了我的抽奖代码,它可以正常工作。(我在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
是-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;
}
}
在线演示
相关文章:
- 为什么即使使用 for 循环遍历我的向量,它也没有输出到控制台?(C++)
- C++无法解决我的问题。我有控制台错误
- 我如何阅读简单的控制台输出
- 当我告诉它通过控制台执行此操作时,我的c ++循环不会停止
- 我的控制台处理程序不处理 CTRL+C,即使设置正确
- 我的控制台正在打印随机单词以及没有执行正确的数学运算
- 在我为我的二维向量提供第一个值后控制台关闭
- 如何在关闭Qt控制台应用程序之前运行我的析构函数?
- 比较两个字符串数组,我的控制台应用程序"stops responding"
- 如果我使用此功能,我的控制台崩溃
- 为什么我的C++控制台在即将接受用户输入时关闭
- 如何将我的控制台应用程序链接到使用 clang++ 作为编译器的 OSX 环境中的 /usr/local/lib 中存在
- 如何使用我的 if-else 语句根据用户权重的输入执行特定操作,然后将其显示到控制台?
- 为什么我的Windows控制台关闭事件处理程序超时
- 为什么将高数字传递给递归功能会使我的控制台停止响应
- 我想让我的控制台更加丰富多彩.如何在用户输入时使用户输入(通过getline获得)
- Windows应用程序启动我的控制台
- 我的控制台给我一个错误
- 如何使我的控制台C++程序在后台运行
- 为什么我的控制台应用程序不等待第 37 行和第 38 行