近日在写链表的时候,将变量值作为形参传进函数中,然后想获取其地址导致出现错误。
- 如下图:
#include "stdio.h"
#include <crtdbg.h>
#include <corecrt_malloc.h>
typedef struct Test
{
int a;
int b;
Test* next;
};
Test* tt = NULL;
Test* head = NULL;
Test aa[] = {
{
1,2,NULL},{
2,3,NULL} };
void Task_ListAdd(Test node);
void init()
{
tt = (Test*)malloc(sizeof(Test));
head = tt;
for (size_t i = 0; i < 2; i++)
{
Task_ListAdd(aa[i]);
}
}
void Task_ListAdd(Test node)
{
tt->next = &node;
tt = &node;
}
int main(void)
{
init();
printf("%d,,%d", head->next->a, head->next->next->a);
return 0;
}
由现象可知,并没有打印出1,2,3
原因:
值传递和址传递的问题,作为形参会新申请一个地址来存放传递进来的变量。
所以我读取函数中的形参地址是我本次程序错误的原因。
原理如下:
最终,改为指针进行地址传递。
#include "stdio.h"
#include <crtdbg.h>
#include <corecrt_malloc.h>
typedef struct Test
{
int a;
int b;
Test* next;
};
Test* tail = NULL;
Test* head = NULL;
Test aa[] = {
{
1,2,NULL},{
2,3,NULL},{
3,4,NULL} };
void Task_ListAdd(Test* node);
void init()
{
head = (Test*)malloc(sizeof(Test));
tail = head;
for (size_t i = 0; i < 3 ; i++)
{
Task_ListAdd(&aa[i]);
}
}
void Task_ListAdd(Test* node)
{
tail->next = node;
tail = tail->next;
}
int main(void)
{
init();
printf("%d,%d,%d", head->next->a, head->next->next->a, head->next->next->next->a);
return 0;
}