我试图将链表节点放入临时变量,但是,当我编辑临时变量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 0 0 0 0
0 0 1 0 0
0 1 1 1 0
0 0 1 0 0
0 0 0 0 0
但是,当我将test
更改为test->puzzle[0][0] = 3
时,test
和currentstate
都转为:
3 0 0 0 0
0 0 1 0 0
0 1 1 1 0
0 0 1 0 0
0 0 0 0 0
答案 0 :(得分:1)
我认为错误就在这里:
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