为什么动态分配的变量不会像静态变量一样发生变化使用地址时

问题描述

head是指向内存的指针,它等于当前内存

void display(node_t **head) {  
    struct node *current = (*head);
    if((*head) == NULL) {  
        printf("List is empty \n");  
        return;  
    }  
    
while(current != NULL) {  
   printf("current->n=%d\n",current->next);  //0 1 2
   printf("head->n=%d\n",head->next);        // 0 0 0 if we assign current to its next 
   current = current->next;                // should it affect to the head because we are
                                           //because we are assigning memory address to another 
}  
}

使用静态变量的示例代码

int *head,*current,c=1;
head=&c;
current=&c;
(*current)++;
在这种情况下,

头和电流会改变

解决方法

因为此时在这里:struct node *current = (*head);您取消引用head。如果head是节点指针的数组,那么当前指向该数组的第一项。

此外,我建议在取消引用head之前检查NULL,因为否则您有SEGFAULT等待发生。

,
while(current != NULL) {  
   printf("current->n=%d\n",current->n);  //0 1 2
   printf("head->n=%d\n",head->n);        // 0 0 0 if we assign current to its next 
   current = current->next;                // should it affect to the head because we are
                                           //because we are assigning memory address to another 
}

忽略命名不一致(是n还是next?,headcurrent是单独的对象-对current所做的任何操作均不会影响head

如果我们画一幅画可能会有所帮助。假设您有一个包含三个节点的列表(我不知道您的节点结构是什么样,所以这很通用):

+---+---+      +---+---+       +---+---+
|   |   |----->|   |   |------>|   |   |---|||
+---+---+      +---+---+       +---+---+

您有一个指向第一个元素的指针(我们将其称为h):

      +---+      +---+---+      +---+---+       +---+---+
   h: |   |----->|   |   |----->|   |   |------>|   |   |---|||
      +---+      +---+---+      +---+---+       +---+---+

您在head函数中的display参数指向h

      +---+
head: |   |
      +---+
        |
        V
      +---+      +---+---+      +---+---+       +---+---+
   h: |   |----->|   |   |----->|   |   |------>|   |   |---|||
      +---+      +---+---+      +---+---+       +---+---+

您使用值为{{1}的current初始化*head,所以h指向列表的第一个节点:

current

每次执行

      +---+
head: |   |
      +---+
        |
        V
      +---+      +---+---+      +---+---+       +---+---+
   h: |   |----->|   |   |----->|   |   |------>|   |   |---|||
      +---+      +---+---+      +---+---+       +---+---+
                   ^
                   |
                 +---+
        current: |   |
                 +---+

将设置current = current->next 指向列表中的下一个元素:

current

您对 +---+ head: | | +---+ | V +---+ +---+---+ +---+---+ +---+---+ h: | |----->| | |----->| | |------>| | |---||| +---+ +---+---+ +---+---+ +---+---+ ^ | +---+ current: | | +---+ +---+ head: | | +---+ | V +---+ +---+---+ +---+---+ +---+---+ h: | |----->| | |----->| | |------>| | |---||| +---+ +---+---+ +---+---+ +---+---+ ^ | +---+ current: | | +---+ 所做的任何事情都不会影响current-它们是独立的对象。

head

在这种情况下,水头和水流将改变。

是的,因为您要同时为int *head,*current,c=1; head=&c; current=&c; while(True): current++; head分配一个新值-但是,currentcurrent++无效。

顺便说一句,这不是有效的C语言-就像您从C语言开始,在Python中完成一样。