【问题标题】:pointer to a pointer in a linked list指向链表中的指针的指针
【发布时间】:2012-08-11 13:55:23
【问题描述】:

我正在尝试通过指向指针的指针来设置链表头。我可以在函数内部看到头指针的地址正在改变,但是当我返回主程序时,它再次变为 NULL。有人可以告诉我我做错了什么吗?

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

           typedef void(*fun_t)(int);
           typedef struct timer_t {
           int   time;
           fun_t func;
           struct timer_t *next;
           }TIMER_T;

          void add_timer(int sec, fun_t func, TIMER_T *head);

             void run_timers(TIMER_T **head);

           void timer_func(int);

           int main(void)
            {
            TIMER_T *head = NULL;
            int time = 1;

            fun_t func = timer_func;

            while (time < 1000) {
              printf("\nCalling add_timer(time=%d, func=0x%x, head=0x%x)\n", time,     

              func, &head);
               add_timer(time, func, head);
               time *= 2;
              }  
              run_timers(&head);

              return 0;
             }

            void add_timer(int sec, fun_t func, TIMER_T *head)
            {
           TIMER_T ** ppScan=&head;
               TIMER_T *new_timer = NULL;
           new_timer = (TIMER_T*)malloc(sizeof(TIMER_T));
               new_timer->time = sec;
               new_timer->func = func;
               new_timer->next = NULL;

               while((*ppScan != NULL) && (((**ppScan).time)<sec))
               ppScan = &(*ppScan)->next;

               new_timer->next = *ppScan;
               *ppScan = new_timer;
               } 

【问题讨论】:

    标签: c pointers linked-list


    【解决方案1】:

    你弄错了。 函数需要取双指针,caller需要取地址:

    {   // caller
        TIMER_T *head = NULL;
        do_something(&head);
    }
    
    void do_something(TIMER_T ** p)  // callee
    {
        *p = malloc(sizeof(TIMER_T*));
        // etc.
    }
    

    以前也有过manymany这样的类似回答。

    【讨论】:

      【解决方案2】:

      由于 C 函数参数是通过它们的而不是它们的地址传递的,并且您没有传递任何变量的地址您的电话:

      add_timer(time, func, head);
      

      所以它们都不会在add_time 函数范围之外更改。

      你可能需要做的是传递head的地址:

      add_timer(time, func, &head);
      

      和:

      void add_timer(int sec, fun_t func, TIMER_T **head)
      {
          TIMER_T ** ppScan = head;
          // ...
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-07-28
        • 2013-08-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-22
        • 1970-01-01
        相关资源
        最近更新 更多