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;
}
You got it the wrong way round. The function needs to take a double pointer, and the caller needs to take the address-of:
{ // caller
TIMER_T *head = NULL;
do_something(&head);
}
void do_something(TIMER_T ** p) // callee
{
*p = malloc(sizeof(TIMER_T*));
// etc.
}
There have been many , many similar answers like this before.
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);
so none of them will be changed outside of add_time
function scope.
What you probably need to do is pass the address of head
:
add_timer(time, func, &head);
and:
void add_timer(int sec, fun_t func, TIMER_T **head)
{
TIMER_T ** ppScan = head;
// ...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.