2011-03-20 96 views
0

今天是我第一次在一段時間內使用C++。我通常是一個Python程序員。 我不斷收到段錯誤,並將其隔離到註釋行。 (註釋去掉,當被註釋掉事業段錯誤的那些)我有段錯誤!

#include <iostream> 
#include <fstream> 
#include <string> 
using namespace std; 
#include "defaultfile.h" 

int main() 
{ 
    ifstream mapin; 
    string map; 
    string s; 
    int i = 0; 
    while (i<=22){i++;top[i][0]="__";i++;};i=0; 
    while (i<=21){i++;frw[i][0]="/";i++;};i=0; 
    while (i<=21){i++;bck[i][0]="\\";i++;};i=0; 
    //while (i<=45){i++;spc[i][0]=" ";i++;};i=0; 
    //while (i<=112){i++;spc[i][1]="n";i++;};i=0; 
    while (i<=22){i++;cout<<top[i][1]<<endl;i++;};i=0; 
    while (i<=21){i++;cout<<frw[i][1]<<endl;i++;};i=0; 
    while (i<=21){i++;cout<<bck[i][1]<<endl;i++;};i=0; 
    //while (i<=45){i++;cout<<spc[i][1]<<endl;i++;};i=0; 
    ... 
} 

標題是:

string top[23][3] = 
{{"", "", ""}, 
... 
{"", "", ""}}; 
string frw[22][3] = 
{{"", "", ""}, 
... 
{"", "", ""}}; 
string bck[22][3] = 
{{"", "", ""}, 
... 
{"", "", ""}}; 
string spc[46][3] = 
{{"", "", ""}, 
... 
{"", "", ""}}; 

編輯: 謝謝。我總是想念和花費一個小時試圖尋找的愚蠢的東西。我需要的只是別人來指出。

+2

標題接縫凌亂 – Daniel 2011-03-20 06:02:16

+0

你爲什麼要初始化那樣的字符串? – quasiverse 2011-03-20 06:02:38

+4

題外話題:空格和換行符是你的朋友! – 2011-03-20 06:03:02

回答

0
//while (i<=112){i++;spc[i][1]="n";i++;};i=0; 

肯定會在spc[46]上發生段錯誤。

1

您正在索引spc一直到112,但只有0-45對第一個索引有效。

2
while (i<=112){i++;spc[i][1]="n";i++;};i=0; 

您定義SPC爲:

string spc[46][3] 
1

數組是基於0。你在每個人上都寫完了。它撞上了SPC,因爲它是最後一個。在另一個你寫入下一個的記憶。

澄清:你做while (i <= 45) { i++; spc[i] ...現在,如果我是45,那麼你增加它到46,你訪問spc[46]這是在邊界之外。所有其他線路都一樣。

此外,你只能初始化每一個字段 - 不知道這是否是故意的。

+0

在使用前增加'i'的好處,並且每個循環實際上兩次。 (另一方面,這也意味着在循環條件下'i == 45'是不可能的,然而'top [23]'將被錯誤地使用) – 2011-03-20 17:43:44