(VC2010快递)2D阵列行为不端

时间:2013-07-16 08:33:47

标签: c++ visual-c++ multidimensional-array grid

我使用VC2010表达并遇到了我无法理解的结果。 我的代码如下:

//

#include "stdafx.h"
#include <iostream>
#include <time.h>

using namespace std;

void main()
{
    const int gridSize = 2;
    int grid[gridSize][gridSize];

    for(int x=1; x <= gridSize; x++){
        for(int y=1; y <= gridSize; y++){
            grid[x][y] = 0;
        }

    }
    for(int i=0; i <= gridSize; i++){
        grid[i][0] = 1; // set the horizontal line to 1's
        grid[0][i] = 1; // set the vertical line to 1's
    }

    int rows = 0;
    while(rows <= gridSize){
        for(int i=0; i<=gridSize; i++){
            cout << grid[i][rows] << " ";
        }
        cout << "\n";
        rows++;
    }

    clock_t wait;
    wait = clock();
    while (clock() <= (wait + 500000));  // Wait for 500 seconds and then continue
    wait=0;
}

我期待此代码导致:

  • 1 1 1
  • 1 0 0
  • 1 0 0

取而代之的是:

  • 1 1 1
  • 1 0 0
  • 1 1 0

我不明白这个代码如何用1填充网格[1] [2]。 有什么想法?

修改 现在无法回答我自己的问题..但我已经解决了格子路径问题! :) 结束此代码以计算网格中的网格路径数量:

#include "stdafx.h"
#include <iostream>
#include <time.h>

using namespace std;

void main()
{
    const int gridSize = 3;
    int grid[gridSize+1][gridSize+1];

    for(int i=0; i <= gridSize; i++){
        grid[i][0] = 1; // set the horizontal line to 1's
        grid[0][i] = 1; // set the vertical line to 1's
    }

    for(int x=1; x <= gridSize; x++){
        for(int y=1; y <= gridSize; y++){
            grid[x][y] = grid[x-1][y] + grid[x][y-1];
        }
    }

    cout << "Amount of lattice paths for a " << gridSize << "x" << gridSize << " grid: " << grid[gridSize][gridSize];

    clock_t wait;
    wait = clock();
    while (clock() <= (wait + 500000));  // Wait for 500 seconds and then continue
    wait=0;
}

感谢您的快速回复:)

1 个答案:

答案 0 :(得分:4)

您的数组索引超出范围,例如:

for(int x=1; x <= gridSize; x++){

应该是:

for(int x = 0; x < gridSize; x++){
                 ^ removed =

你应该为索引值[0 to gridSize)运行你的循环,是的,这个行为错误在C标准中被称为Undefined behavior