我正在尝试将链表节点放入临时变量中,但是,当我编辑临时变量test
时,原始currentstate
变量也会更改。
这是代码:
struct states * BFSearch(struct states* initial)
{
int i = 0, j = 0,k=0,l=0;
struct states* currentstate = (struct states*)malloc(sizeof(struct states));
struct states* temp = (struct states*)malloc(sizeof(struct states));
Enqueue(initial);
while(front != NULL && rear != NULL)
{
currentstate = Dequeue();
if (GoalTest(currentstate))
{
return(currentstate);
}
else
{
for(i = 0; i<5; i++)
{
for(j = 0; j<5; j++)
{
if (currentstate->toggled[i][j] == 0)
{
test = currentstate;
test->puzzle[0][0] = 3;
for (k = 0; k < 5; k++)
{
for (l = 0; l < 5; l++)
{
printf("%d ", currentstate->puzzle[k][l]);
}
printf("n");
}
printf("n");
for (k = 0; k < 5; k++)
{
for (l = 0; l < 5; l++)
{
printf("%d ", test->puzzle[k][l]);
}
printf("n");
}
printf("n");
}
}
}
}
}
}
currentstate
谜题如下所示:
0 00 0 0
0 0 0 0 0
0 0 1 0 0
0 1 1 1 0
0 0 1 0 0
但是,当我只是将test
更改为test->puzzle[0][0] = 3
时,它们test
和currentstate
都变成了这个:
3 0 00 0
0 0 0 0 0
0 0 1 0 0
0 1 1 1 0
0 0 1 0 0
我认为错误就在这里:
if (currentstate->toggled[i][j] == 0){
test = currentstate;
test->puzzle[0][0] = 3;
它应该是:
if (currentstate->toggled[i][j] == 0){
*test = *currentstate;
test->puzzle[0][0] = 3;
当您执行以下操作时:
test = currentstate;
然后测试指向 currentstate
的同一地址,如果这样做:
*test = *currentstate;
您正在将currentstate
指向的内容复制到test
指向的内容