如图,指针在进入函数前后的值不同,不知道为什么。求大神解答
第二次p0的sno未进入前是123,进入函数后,就变成234了,然而我并没有进行赋值操作。
为题主补充了代码,并增加了一点指针地址的输出。
#include <stdio.h>
typedef struct student
{
struct student *next;
int sno;
} Stu;
Stu* insert(Stu *node, Stu stu)
{
if(node != NULL)
{
printf("insert func, %d, %p\n", node->sno, node);
}
Stu *p0, *p1;
p0 = node;
p1 = &stu;
if( p0 == NULL )
{
node = p1;
p1->next = NULL;
}
else
{
while(p0->next != NULL)
p0 = p0->next;
p0->next = p1;
p1->next = NULL;
}
return node;
}
int main()
{
Stu *p0 = NULL;
Stu p1, p2;
p1.sno = 123;
p2.sno = 234;
p2.next = NULL;
printf("p1 %p, p2 %p\n", &p1, &p2);
p0 = insert(p0, p1);
printf("after first insert, %d\n", p0->sno);
insert(p0, p2);
}
某个可能的输出:
p1 0x28cc64, p2 0x28cc5c
after first insert, 123
insert func, 234, 0x28cc44
原因可能是返回了临时变量的引用出了问题, 在5.1版本中优化了
重新组织一下思路吧:
开始的
Stu *inset(Stu *node, Stu stu)
这个属于值传递,此处的stu
只是个临时变量,然后返回的node
指向了stu
,也就是第二个参数,这个临时变量的地址,因此,再次调用insert
函数时候,仍然指向了第二个参数的地址,也就是p2
。所以会输出234
, 而Stu *inset(Stu *node, Stu& stu)
这个引用传递,则不同,这里的stu
就在第一次调用就是main
函数的p1
这个实例,第二次调用就是p2
。所以没有异常发生。所以最好不要返回临时变量的引用。
至于
gcc 5.1
的优化--可能是对自定义的类或者结构体,本身就作为引用了,个人猜测。。。。