我不明白为什么当我用 *p1 初始化指针时没有遇到错误,其中 p1 是双指针

问题描述 投票:0回答:1

程序没有特定功能;我目前正在研究列表,我很难理解为什么我在

Node*curr=*root;
行中没有得到编译错误,我不应该使用
Node*curr
使用地址初始化
&?
吗?但是当我设置双精度时指针和一个指针,然后我用
*p
初始化第二个指针,其中
p
是双指针,我收到编译错误,程序甚至无法运行。这两种情况对我来说似乎都是一样的,我看不出有什么区别。

#include<stdio.h>
#include<stdlib.h>
    
    typedef struct Node{
     int x;
     struct Node*next;
     }Node;
    
    
     void insert_end(Node**root,int value){
    
         Node*new_node=malloc(sizeof(Node));
         new_node->next=NULL;
         new_node->x=value;
          //We have to use the loop to reach the
           //  end of the list where we add our additional box
           Node*curr=*root;
           while(curr->next!=NULL){
            curr=curr->next;
    
           }
           curr->next=new_node;
     }
    
    
     int main(){
         Node *root=malloc(sizeof(Node));
         root->x=15;//1o element
         root->next=NULL;
    
      //the last element of a listis always initialize with null
      //exit loop when *next=NULl
    
      //it matters the order of freeing the memory
      insert_end(&root,-2);
      for( Node*curr=root;curr!=NULL;curr=curr->next){
    
          printf("%d\n",curr->x);
    
      }
    
     return 0;
     }
c list pointers ampersand double-pointer
1个回答
0
投票

为了清晰起见,让塔给这些东西赋值。

main()
中,假设堆栈从地址100000开始。局部变量
root
分配在那里,所以它的地址是1000000。

malloc()
从堆中返回一些东西,假设它是地址100,所以
root
包含100。

您调用

insert_end()
,参数被放入堆栈中,因此
root
本地有一个新版本的
insert_end()
。假设
main()
总共需要 8 个字节用于本地存储,并且堆栈存储向下扩展(减少地址),因此
insert_end()
的参数分配在地址 99992(第一个参数
root
)和 99988(第二个参数
value
)。

root

中的
main()
root
中的
insert_end()
是不同内容的不同变量。
root
inssert_end()
的内容是
root
main()
的地址,即100000。

在下面,您将

*root
分配给
curr
,因此您将按照
root
insert_end()
中的地址 100000 到
root
中的
main()
并取该值 - 100。将 100 分配给
curr
,因此
curr
引用您最初从
malloc()
获得的内存。

为了更好地理解,考虑

root
的类型是
Node **
,当您将
*
添加到指针变量时,您将其从类型中删除,因此
*root
Node *
类型,这就是与
Node *curr
相同。

© www.soinside.com 2019 - 2024. All rights reserved.