我試圖實現以下功能。 它是做什麼的:我無法理解爲什麼這段代碼給出了段錯誤
- 需要座標。
- 將權重分配給周圍的單元格。
- 在地圖中存儲這些權重和單元格方向。
- 通過地圖循環。從最低的重量開始。
- 調用再次移動鄰居單元座標。
代碼片段:
120 void move(const int x, const int y)
121 {
122 map<int, int> nextDir;
123 map<int, int>::iterator it;
124 if((x == maxX - 1) && (y == maxY - 1))
125 {
126 int groundCopy[maxX][maxY];
127 memcpy(((void *)&groundCopy), ((void *)&ground), sizeof(groundCopy));
128 traceBack(x, y);
129 memcpy(((void *)&ground), ((void *)&groundCopy), sizeof(ground));
130 printPPM();
131 }
132 for(int i = 0; i < 8; ++i)
133 {
134 if(!isValid(x + dirX[i], y + dirY[i]))
135 continue;
136 int temp = weight[x][y][0] + ground[x + dirX[i]][y + dirY[i]] + disWeight(x, y, x + dirX[i], y + dirY[i]);
137 if(!(weight[x + dirX[i]][y + dirY[i]][0] == numeric_limits<int>::max()))
138 temp += weight[x + dirX[i]][y + dirY[i]][0];
139 if(temp < weight[x + dirX[i]][y + dirY[i]][0])
140 {
141 weight[x + dirX[i]][y + dirY[i]][0] = temp;
142 weight[x + dirX[i]][y + dirY[i]][1] = 7 - i;
143 nextDir[temp] = i;
144 }
145 else
146 continue;
147 }
148 for(it = nextDir.begin(); it != nextDir.end(); ++it)
149 move(x + dirX[it->second], y + dirY[it->second]);
150 }
回溯信息:
Program received signal SIGSEGV, Segmentation fault.
0x0000000000401760 in move (x=<error reading variable: Cannot access memory at address 0x7fffff5ab18c>, y=<error reading variable: Cannot access memory at address 0x7fffff5ab188>) at codes/terrainExample.cpp:121
121 {
(gdb) bt
#0 0x0000000000401760 in move (x=<error reading variable: Cannot access memory at address 0x7fffff5ab18c>, y=<error reading variable: Cannot access memory at address 0x7fffff5ab188>) at codes/terrainExample.cpp:121
#1 0x0000000000401bfa in move (x=0, y=1) at codes/terrainExample.cpp:149
#2 0x0000000000401bfa in move (x=0, y=0) at codes/terrainExample.cpp:149
#3 0x0000000000401dbb in solve() at codes/terrainExample.cpp:167
#4 0x0000000000401f1c in main() at codes/terrainExample.cpp:186
什麼是錯我的執行?
以下是鏈接到代碼和Valgrind的日誌如果需要的話: https://www.dropbox.com/s/5m8zfxubq6lcl8o/terrainExample.cpp?dl=0 https://www.dropbox.com/s/wq7ob1uevwutsov/logfile.out?dl=0
在這段代碼中我使用矢量地圖代替的。
使用調試器檢查代碼時檢查您的索引變量,並確保您訪問數組的邊界。 –
第134行我正在那樣做。 bool isValid(const int x,const int y){if((x <0)||(y <0) || (x> = maxX)||(y> = maxY))return false;返回true;} 在調試也我檢查。 – prad