2012-08-15 133 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类似的这样的答案。