使用一小段代码进行分段错误(核心转储)错误

时间:2016-04-25 18:44:00

标签: c struct segmentation-fault

我有时会得到上面提到的错误,我知道它是由于以下代码但是看不出可能是什么原因,因为我对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]);

1 个答案:

答案 0 :(得分:0)

示例代码中缺少某些部分,但问题很可能在于访问maprand()的定义也很重要。如果它提供介于-1和1之间的值,则最终会出现分段错误。

使用valgrind和其他工具获取更多信息,分析错误的原因是什么。