使用VC2010表達我遇到了一個難以理解的結果。 我的代碼如下:(VC2010 express)二維陣列行爲異常
//
#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] [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;
}
感謝您的快速回復:)
'i <= gridSize' for循環 - 即時UB!你甚至不需要付錢! – 2013-07-16 08:35:35
用調試器開始你的一天:) – 0decimal0