【问题标题】:My console crash if i use this function如果我使用此功能,我的控制台会崩溃
【发布时间】:2018-03-23 21:36:56
【问题描述】:

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

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

【问题讨论】:

  • 您的代码非常需要格式化。
  • 提示:调用函数时xp-xs 是什么? grid[y][xp-xs] 是哪个元素?是时候了解调试器的工作原理了

标签: c++ arrays function crash codeblocks


【解决方案1】:

问题是您在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;
  }
}

Online demo

【讨论】:

    猜你喜欢
    • 2016-07-17
    • 2017-04-09
    • 1970-01-01
    • 2012-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-03
    • 1970-01-01
    相关资源
    最近更新 更多