【问题标题】:Simple and double pointers formulas简单和双指针公式
【发布时间】:2017-10-24 10:31:38
【问题描述】:

我做了删除 fct 二叉树头,它工作!但我没有做任何努力,我依赖调试器。

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

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

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

【问题讨论】:

    标签: c pointers tree double binary-tree


    【解决方案1】:

    上图显示了指向指针的指针的内存表示。第一个指针 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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多