/*main函数将一个空指针的地址(二级指针)传入多个子函数,每个子函数都需要添加新节点,形成链表,要求不改变首节点所指向的地址,*/
typedef struct id_node_t
{
int id;
struct id_node_t *next;
} ID_NODE_T;
void test1(ID_NODE_T **p)
{
int i = 3;
int first = 1;
ID_NODE_T *tmp_node = NULL;
ID_NODE_T *tmp_array = NULL;
while(i--)
{
tmp_node = (ID_NODE_T*)malloc(sizeof(ID_NODE_T));
memset(tmp_node,0,sizeof(ID_NODE_T));
tmp_node->id = i;
if(first)
{
*p = tmp_node;
tmp_array = tmp_node;
first = 0;
}
else
{
tmp_array->next = tmp_node;
tmp_array = tmp_array->next;
}
}
return;
}
void test2(ID_NODE_T **p)
{
ID_NODE_T *temp_node = *p;
int i = 3;
int first = 1;
ID_NODE_T *tmp_node = NULL;
ID_NODE_T *tmp_array = NULL;
printf("%s %p\n",__func__,temp_node);
printf("%s %p\n",__func__,*p);
while((*p)->next)
{
(*p) = (*p)->next;
}
while(i--)
{
tmp_node = (ID_NODE_T*)malloc(sizeof(ID_NODE_T));
memset(tmp_node,0,sizeof(ID_NODE_T));
tmp_node->id = 9;
if(first)
{
(*p)->next = tmp_node;
tmp_array = tmp_node;
first = 0;
}
else
{
tmp_array->next = tmp_node;
tmp_array = tmp_array->next;
}
}
printf("%s %p\n",__func__,*p);
*p = temp_node;
printf("%s %p\n",__func__,temp_node);
printf("%s %p\n",__func__,*p);
return ;
}
void main(void)
{
ID_NODE_T *p = NULL;
test1(&p);
test2(&p);
while(p)
{
printf("----%d\n",p->id);
p = p->next;
}
return ;
}
执行结果
test2 0x9594008
test2 0x9594008
test2 0x9594028
test2 0x9594008
test2 0x9594008
----2
----1
----0
----9
----9
----9