gpt4 book ai didi

c - 简单和双指针公式

转载 作者:太空宇宙 更新时间:2023-11-04 04:20:55 25 4
gpt4 key购买 nike

我制作了 delete fct 二叉树 header ,它成功了!但我没有做任何努力,我依赖于调试器。

你能解释一下简单指针、双指针和值之间的关系吗?

Tree **P2,*P1,P; //(P consider it for explanation only)
P1=&P2;

//what type are these
(*P2)->data;
&(*P2)->data;
P1->data;
*P1->data;

最佳答案

enter image description here上图显示了指向指针的指针的内存表示。第一个指针 ptr1(P2 在您的例子中)存储第二个指针 ptr2 的地址,第二个指针 ptr2(P1 在您的例子中)存储变量的地址。

#include <stdio.h>
#include <stdlib.h>

typedef struct _s {
int data;
} Tree;

int main(int argc, char *args[])
{

/*
* Arrow operator example
* foo->bar is equivalent to (*foo).bar
* it gets the member called 'bar' from the struct that 'foo' points to.
*/

Tree **P2,*P1;
P1 = (Tree*)malloc(sizeof(Tree));
P1->data = 789;
//P1=&P2; // It's wrong, Incompatible pointer types Tree* and Tree***
P2 = &P1; // It's right, p2 points to address of p1
printf("%d\n", (*P2)->data); // same as (**P2).data
printf("%p\n", (void*) &(*P2)->data); // same as &(**P2).data, (void* casting to print address)
printf("%d\n", P1->data); // same as (*P1).data
//printf("%d",*P1->data); // same as *(P1->data), it's already dereferenced type, you're trying to dereference again??
free(P1);


return 0;
}

关于c - 简单和双指针公式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46908191/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com