2012-08-15 110 views
0

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

回答

1

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

你得到它的南轅北轍。該功能需要採取雙指針,並且呼叫者需要採取地址的:

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

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

有以前一直manymany類似的這樣的答案。