2013-07-16 66 views
0

使用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; 
} 

感謝您的快速回復:)

+1

'i <= gridSize' for循環 - 即時UB!你甚至不需要付錢! – 2013-07-16 08:35:35

+0

用調試器開始你的一天:) – 0decimal0

回答

4

你數組索引超出結合,例如:

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

應該是:

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

您應該運行您環路我指數值爲[0 to gridSize),而且這種行爲不端在C標準中被稱爲Undefined behavior

+1

haha​​ha這種行爲錯誤被稱爲C中的未定義行爲lol – 0decimal0

+1

對,你其實是想讓for循環爲<=,只是忘記在gridSize + 1上聲明數組。我試圖解決項目第十五號問題。 – Pwnball

+0

@蓬球祝你好運Pwnball! –