[英]difference between structure pointers in c
给出以下结构:
struct node
{
int data;
struct node *next;
};
以下两个功能之间的区别是什么:
void traverse(struct node *q);
和
void traverse(struct node **q);
如何使用它们?
一个带一个指向节点的指针:
void traverse(struct node *q);
另一个指向节点的指针(注意函数的名称更改)。
void insert(struct node **q);
当您需要访问指向的内容时,使用前者。 当您需要访问您可能需要修改从呼叫侧的实际指针变量作为潜在的进出参数是什么pointed- 与 IE浏览器使用后者。
前者的一个很好的例子是遍历您的链表的枚举。 您无需修改列表头,只需要一个指向起始节点的指针即可。
后者的一个很好的例子是,当您将节点压入堆栈时,列表头指针本身将在完成功能之前更改。
像C语言中的所有事物(不支持数组)一样,如果要将内容修改为输出参数,则需要将参数声明为正式的指针类型,并传递要修改的对象的地址。 在后一种情况下(我认为这是引起混乱的情况),我们需要修改的是指针变量本身,因此必须将其声明为指针到指针,然后将指针的地址传入。
示例大声说,因此请看一下:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
void traverse(struct node* p)
{
while (p)
{
printf("%d\n", p->data);
p = p->next; // note. modifies only our local variable p.
// caller side uneffected.
}
}
void insert(struct node **pp, int data)
{
struct node *p = malloc(sizeof(*p));
p->data = data;
p->next = *pp;
*pp = p; // note: save new list head here.
}
int main(int argc, char *argv[])
{
struct node *head = NULL;
insert(&head, 1);
printf("head = %p\n", head);
insert(&head, 2);
printf("head = %p\n", head);
insert(&head, 3);
printf("head = %p\n", head);
traverse(head);
// yes, I know its leaking memory. that isn't the subject of this question.
return 0;
}
输出量
head = 0x1001000e0
head = 0x100103b40
head = 0x100103b50
3
2
1
第一个是单个指针。 它可以修改数据,然后修改数据,但不能修改传递给函数的参数所指向的内容。 通常在已经为该结构分配空间时使用。
q->data = 4; /* works */
q = malloc(sizeof(struct node)); /* new memory CANNOT be seen outside the function */
第二个是双指针,因此您不仅可以修改字段数据和next,还可以为其分配空间,并在函数外部看到新的空间。
(*q)->data = 4; /* works */
*q = malloc(sizeof(struct node)); /* new memory CAN be seen outside the function */
struct node *q
表示变量q是指向节点的指针。
struct node **q
表示变量q是指向节点的指针。
struct node theNode;
struct node *p1 = &theNode;
struct node **p2 = &p1;
这类似于按值传递和按引用传递之间的区别。
在这里,通过struct node *q
传递可以修改q指向的内容并使输入指针指向的内容生效,但不能修改指针本身。 因此,这类似于passing by value
,其中q是struct node *
类型struct node *
在通过struct node **q
传递时,可能会更改所有内容,包括输入指针的值和地址(可能是结构节点* p;和&p传递),并导致结果为p。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.