什么在破坏这个多维数组的堆栈?

问题描述 投票:0回答:1

该脚本产生一个斐波那契螺旋,从中心开始向外分支。虽然输出正确,但我收到一条错误消息:

“运行时检查失败#2 - 变量'fibArr'周围的堆栈已损坏。”

我已经尝试将fibCount减少1,但这导致中心数为0,我不想要。

int fibFunc(int);


int main() {
    //--setting variables
    const int rowCount = 5, colCount = 5;
    const int fibCount = rowCount * colCount - 1;
    static int f; 
    int i, j;


    //--creating  grid
    int grid[rowCount][colCount] = { 0 };

    //Create fibArr
    f = fibCount;
    int fibArr[fibCount];

    while (f >= 0) {
        fibArr[f] = fibFunc(f);
        f--;
    }


    //directions settings
    enum direction {
        DOWN, RIGHT, UP, LEFT
    } d = DOWN;

    //spiral loop
    int R = 0, C = 0; //R for row, C for column
        f = fibCount;
        while (f >= 0) {

            grid[R][C] = fibArr[f];

            f--;


            if (d == DOWN) {
                if (grid[R+1][C] == 0)
                    R++;
                else d = RIGHT;
            }


            if (d == RIGHT) {
                if (grid[R][C+1] == 0)
                    C++;

                else d = UP;
            }

            if (d == UP) {
                if (grid[R-1][C] == 0)
                    R--;
                else d = LEFT;
            }

            if (d == LEFT) {
                if (grid[R][C-1] == 0)
                    C--;
                else {
                    d = DOWN;
                    R++;
                } 
            }
        }

    printFib(fibArr, fibCount); 
    for (i = 0; i < rowCount; i++) {
        for (j = 0; j < colCount; j++) {
            cout << setw(7) << grid[i][j];
        }
        cout << endl;
        cout << endl;
    }

    system("pause>nul");
}   

int fibFunc(int n) {
    if (n == 0 || n == 1)
        return 1;
    else
        return fibFunc(n - 1) + fibFunc(n - 2);
}

产量

75025     55     89    144    233

46368     34      1      2    377

28657     21      1      3    610

17711     13      8      5    987

10946   6765   4181   2584   1597
c++ multidimensional-array stack-overflow
1个回答
0
投票

正如juanchopanza所指出的,数组索引从0到大小-1。

const int rowCount = 5, colCount = 5;
const int fibCount = rowCount * colCount - 1;

这将导致:

fibCount = 24 = ( 5 * 5 ) - 1;

再往下,在你的while循环:

int R = 0, C = 0; //R for row, C for column
f = fibCount;
while (f >= 0) {

    grid[R][C] = fibArr[f]; // f = 24; size = 24;

    ...

}

在这里,您从数组f​​ibArray中获取一个值为24的值。最后一个索引为23。


将其更改为:

const int fibCount = rowCount * colCount;

然后在你的while循环之前:

f = fibCount - 1;

除此之外,我会使用这样的单维数组:

int rows = 5, cols = 5;
char* tst = new char[ rows * cols ];

int select_row = 2;
int select_col = 3;

tst[ select_row * cols + select_col ] = 65;
char c = tst[ select_row * cols + select_col ];

delete[] tst;
© www.soinside.com 2019 - 2024. All rights reserved.