c -我如何修复这个嵌套循环中的分割错误?



我有一个迷宫引导程序,但是它被卡在一行中。它是鼠标定位器,它通过指针数组搜索在迷宫中找到"M"或鼠标。代码不断给出分段错误

void iterative_search(char **maze, int rows, int cols, char *directions) {
int x = -1, y = -1;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (maze[i][j] == 'M') { //<- segmentation fault happens here.
break;
}
}
if (maze[x][y] == 'M') {
break;
}
}

if (x == rows && y == cols) {
printf("Error: Jerry not found in the maze.n");
return;
}
for (int i = 0; directions[i] != ''; i++) {
int new_x = x;
int new_y = y;
switch (directions[i]) {
case 'N':
new_x--;
break;
case 'E':
new_y++;
break;
case 'S':
new_x++;
break;
case 'W':
new_y--;
break;
default:
continue;
}

if (new_x >= 0 && new_y >= 0 && new_x < rows && new_y < cols &&
(maze[new_x][new_y] == ' ' || maze[new_x][new_y] == 'C')) {
if (maze[x][y] != 'M') {
maze[x][y] = '.';
}
x = new_x;
y = new_y;
if (maze[x][y] == 'C') {
printf("Jerry found the cheese at (%d, %d)!n", x, y);
break;
}
}
}

下面是分配和调用函数

的其余代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void iterative_search(char **maze, int rows, int cols, char *directions);
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Error: Please provide two input files via command line arguments.n");
return 1;
}
FILE *maze_file = fopen(argv[1], "r");
FILE *directions_file = fopen(argv[2], "r");
if (!maze_file || !directions_file) {
printf("Error: Could not open input files.n");
return 1;
}
int rows, cols;
// Read in maze from maze_file and store in 2D array
fscanf(maze_file, "%d %d", &rows, &cols);
fgetc(maze_file); // consume the newline character after reading rows and cols
char **maze = malloc(rows * sizeof(char *));
for (int i = 0; i < rows; i++) {
maze[i] = malloc((cols + 1) * sizeof(char));
fgets(maze[i], cols + 1, maze_file);
}
fclose(maze_file);

char *directions = NULL;
size_t len = 0;
ssize_t read;
while ((read = getline(&directions, &len, directions_file)) != -1) {
iterative_search(maze, rows, cols, directions);
}
fclose(directions_file);

// Write iterative search output to file
FILE *iterative_output = fopen("iterative_output.out", "w");
if (iterative_output) {
for (int i = 0; i < rows; i++) {
fprintf(iterative_output, "%s", maze[i]);
}
fclose(iterative_output);
} else {
printf("Error: Could not create iterative_output.out file.n");
}

// Free dynamically allocated memory and close files
for (int i = 0; i < rows; i++) {
free(maze[i]);
}
free(maze);
return 0;
}

我认为问题在这里:

int x = -1, y = -1;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (maze[i][j] == 'M') { //<- segmentation fault happens here.
break;
}
}
if (maze[x][y] == 'M') {
break;
}
}

你有这些变量xy在这个函数中广泛使用。然而,它们实际上从来没有被设置成任何有用的东西。相反,你有这些循环局部变量ij

你的意思可能是:

for (y = 0; y < rows; y++) {
for (x = 0; x < cols; x++) {

使xy被设置为目标坐标。

你对maze[-1][-1]的访问导致了未定义的行为,这可能是你的分段错误的原因。

你没有提供足够的信息让我测试这个修复,所以可能还有其他问题。

相关内容

  • 没有找到相关文章

最新更新