我正在編寫解決迷宮的程序。它從開始廣場「o」開始,以「*」結束。 「#」是牆壁和「。」是可以探索的正方形。該算法是在程序開始時將開始方塊添加到空隊列中。之後的每一個後續步驟都是將隊列從隊列中取出,並檢查它是否是已記錄的方塊,是完成方塊還是可檢測。如果可以探索,則將相鄰的非牆壁方塊添加到隊列中。我的問題是,當我將起始方塊添加到隊列中時,出現了分段錯誤,我不知道爲什麼。下面是相關代碼:將結構插入隊列時出現分段錯誤
mazeQ.c:
#include <stdio.h>
#include <stdlib.h>
#include "QueueInterface.h"
int main(void)
{
Queue Q;
InitializeQueue(&Q);
int row;
int column;
int x;
int y;
scanf("%d %d", &column, &row); //scan dimensions of maze
char input[row][column];
ItemType maze[row][column];
for(x = 0; x <= row; x++) {
fgets(input[x],column+2,stdin);
}
row++;
for (x = 1; x < row; x++){
for (y = 0; y < column; y++) {
maze[x][y].squareType = input[x][y];
maze[x][y].xCoordinate = x-1;
maze[x][y].yCoordinate = y;
maze[x][y].recordedSquare = 0;
}
}
for(x = 1; x < row; x++){
for(y = 0; y < column; y++) {
if (maze[x][y].squareType == 'o')
Insert(maze[x][y],&Q); //INSERTED HERE
}
}
for (x = 1; x < row; x++) {
for (y = 0; y < column; y++) {
printf("%c", maze[x][y].squareType);
}
printf("\n");
}
}
UserTypes.h:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char squareType;
int xCoordinate;
int yCoordinate;
int recordedSquare;
} ItemType;
下面的兩個文件必須保持他們的方式。 QueueImplementation.c:
#include <stdio.h>
#include <stdlib.h>
#include "QueueInterface.h"
void SystemError(char *errorMsg) {fprintf(stderr,errorMsg);}
void InitializeQueue(Queue *Q)
{
Q->Front = NULL;
Q->Rear = NULL;
}
int Empty(Queue *Q)
{
return (Q->Front == NULL);
}
int Insert(ItemType R, Queue *Q)
{
QueueNode *Temp;
/* attempt to allocate */
Temp = (QueueNode *) malloc(sizeof(QueueNode)); /* a new node */
if (Temp == NULL) { /* Temp = NULL signals allocation */
SystemError("system storage is exhausted"); /* failure */
return 0;
} else {
Temp->Item = R;
Temp->Link = NULL;
if (Q->Rear == NULL) {
Q->Front = Temp;
Q->Rear = Temp;
} else {
Q->Rear->Link = Temp;
Q->Rear = Temp;
}
}
return 1;
}
QueueInterface.h:
#include "UserTypes.h" /* get ItemType definition */
typedef struct QueueNodeTag {
ItemType Item;
struct QueueNodeTag *Link;
}QueueNode;
typedef struct { /* a queue is empty iff */
QueueNode *Front; /* its Front == NULL */
QueueNode *Rear;
}Queue;
/* defined operations */
extern void InitializeQueue(Queue *Q);
/* Initialize the queue Q to be the empty queue */
extern int Empty(Queue *Q);
/* Returns TRUE == 1 if and only if the queue Q is empty */
extern int Full(Queue *Q);
/* Returns TRUE == 1 if and only if the queue Q is full */
extern int Insert(ItemType R, Queue *Q);
/* If Q is not full, insert a new item R onto the rear of Q */
extern int Remove(Queue *Q, ItemType *F);
/* If Q is non-empty, remove the frontmost item of Q and put it in F */
該計劃是由輸入mazeQ < sampleMaze
運行sampleMaze
12 10
############
#..........#
#.#.######.#
#.#....#...#
#.###.*#.#.#
#...####.#.#
#.#.#..#.#.#
#.#.#.##.#.#
#o#......#.#
############
你有沒有考慮過使用調試器? –
請注意<= here:'for(x = 0; x <= row; x ++)' –
@EdHeal我已經按照gdb調試分段錯誤的指導,但是我沒有找到問題。 – user1684402