C语言 指针到指针类型的变量是怎样的?


struct node
{
int data;
struct node *link;
};
struct node *addnode(struct node **head);
int main()
{
struct node *head = NULL;
addnode(&head);
return 0;
}

struct node *addnode(struct node **ptrTohead)
{
if (*ptrTohead == NULL)
{
struct node *newNode = (struct node*) malloc(sizeof(struct node));
*ptrTohead = newNode;
}
}

我在C中做了一个链表实现,遇到了这个代码:我不明白的是&headstruct node **类型的,毕竟*head是一个存储地址的指针,&head获得头变量的地址。这是指针对指针的指针吗?

我是这样想的:

//                head ----> |___2______| 
/memory address/  100           200
// &head is 100 and is of type struct node *

研究这个简单的示范程序。

#include <stdio.h>
int main(void) 
{
int x = 10;

int *p = &x;
printf( "The variable x stores the value %dn", x );
printf( "Its address is %pn", ( void * )&x );

printf( "nThe pointer p stores the address of the variable x %pn", 
( void * )p );
printf( "Dereferencing the pointer p we will get x equal to %dn" , *p );
printf( "The address of the pointer p itself is %pn", ( void * )&p );

int **pp = &p;

printf( "nThe pointer pp stores the address of the pointer p %pn", 
( void * )pp );
printf( "Dereferencing the pointer pp we will get the address stored in p %pn",
( void * )*pp );
printf( "Dereferencing the pointer pp two times "
"we will get  x equal to %dn", **pp );
int y = 20;

printf( "nBecause dereferencing the pointer ppn"
"we have a direct access to the value stored in pn"
"we can change the value of pn" );
*pp = &y;           
printf( "nNow the pointer p stores the address of the variable y %pn", 
( void * )p );
printf( "Dereferencing the pointer p we will get y equal to %dn" , *p );
printf( "The address of the pointer p itself was not changed %pn", ( void * )&p );

return 0;
}

程序输出可能看起来像

The variable x stores the value 10
Its address is 0x7fffd5f6de90
The pointer p stores the address of the variable x 0x7fffd5f6de90
Dereferencing the pointer p we will get x equal to 10
The address of the pointer p itself is 0x7fffd5f6de98
The pointer pp stores the address of the pointer p 0x7fffd5f6de98
Dereferencing the pointer pp we will get the address stored in p 0x7fffd5f6de90
Dereferencing the pointer pp two times we will get  x equal to 10
Because dereferencing the pointer pp
we have a direct access to the value stored in p
we can change the value of p
Now the pointer p stores the address of the variable y 0x7fffd5f6de94
Dereferencing the pointer p we will get y equal to 20
The address of the pointer p itself was not changed 0x7fffd5f6de98

即变量ppp都是指针。不同之处在于,指针p指向类型为int的对象(指向变量xy),而指针pp指向类型为int *的变量p。解引用这些指针中的任何一个,你都可以直接访问指向对象,并可以更改它(如果它不是常量对象)。

main中,head是指向struct节点的指针。表达式&head是指向struct node的指针的地址。ptrTohead是函数addnode的形式形参,是指向struct节点的指针。&head的值可以赋值给ptrTohead,因为它是指向struct节点的指针的地址,而指向struct节点的指针的地址是初始化指向struct节点的指针的合适值。

注意&head而不是指向结构节点的指针。它是指向struct node的指针的地址。还要注意,*head不是指针。*head是struct节点,head是指向struct节点的指针。

最新更新