2016-04-25 54 views
-2

我有時會收到上面提到的錯誤,我知道它是由於下面的代碼,但沒有看到有什麼能原因,作爲即時通訊仍然很新的C.分割故障(核心轉儲)誤差小塊代碼

struct Point playerPosition; 
int counter = 0; 
do { 
    playerPosition.x = rand() % mapLength; 
    playerPosition.y = rand() % mapHeight; 
    counter++; 
    printf("The current tile that is being tried is: %c\n", map[playerPosition.x][playerPosition.y]); 
} while((counter < (mapLength*mapHeight)) && ((map[playerPosition.x][playerPosition.y] == '#') || (map[playerPosition.x][playerPosition.y] == 'P'))); 
printf("A tile was found at %d %d, with the tile being %c\n", playerPosition.x, playerPosition.y, map[playerPosition.x][playerPosition.y]); 
+0

哪裏定義了'maplength' /'mapheight',它們與'map'有什麼關係? –

+1

除了'struct Point'(儘管我們可以猜到它的聲明)請參閱:[**如何創建一個最小,完整和可驗證的示例**](http://stackoverflow.com/help/mcve) 「 –

+1

我在代碼片段中看不到」map「被定義的任何地方,這肯定會導致段錯誤 –

回答

0

您的示例代碼中缺少一些部分,但問題很可能在訪問maprand()的定義也是重要的。如果它傳遞-1和1之間的值,則最終會出現分段錯誤。

使用valgrind和其他工具來獲取更多信息,分段故障的原因是什麼。