簡體   English   中英

指向鏈表中的指針的指針

[英]pointer to a pointer in a linked list

我正在嘗試通過指向指針的指針設置鏈接列表頭。 我可以在函數內部看到頭指針的地址正在更改,但是當我返回主程序時,它再次變為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;
               } 

您弄錯了方法。 函數需要帶一個雙指針,而調用者需要帶以下地址:

{   // caller
    TIMER_T *head = NULL;
    do_something(&head);
}

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

已經有許多許多以前類似的答案是這樣的。

由於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;
    // ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM