0

I'm trying to set a linked list head through pointer to a pointer. I can see inside the function that the address of the head pointer is changing but as i return to the main progran it becomes NULL again. can someone tell me what I'm doing wrong ??

           #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;
               } 
4

2 回答 2

2

你弄错了。函数需要取一个双指针,调用需要取地址:

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

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

以前有很多很多类似的答案。

于 2012-08-15T09:02:58.187 回答
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;
    // ...
}
于 2012-08-15T09:01:25.007 回答