指向链表中的指针的指针 [英] pointer to a pointer in a linked list

查看:238
本文介绍了指向链表中的指针的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

由于C函数参数是通过传递其而不是通过其地址传递的, strong>,并且您不会在调用中传递任何变量的地址:

Since C function arguments are passed by their value and not by their address and you don't pass the address of any variable in your call:

add_timer(time, func, head);

因此它们都不会在add_time函数范围之外更改.

so none of them will be changed outside of add_time function scope.

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

What you probably need to do is pass the address of head:

add_timer(time, func, &head);

和:

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

这篇关于指向链表中的指针的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆