C链接列表临时变量

时间:2016-02-12 03:41:11

标签: c variables linked-list

我试图将链表节点放入临时变量,但是,当我编辑临时变量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时,testcurrentstate都转为:

  

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

1 个答案:

答案 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

指向的内容