The pointer value changes after the C language pointer enters the function

  c++, question

As shown in the figure, the pointer has different values before and after entering the function. I don’t know why. Seek a great god’s solution

clipboard.png

The sno of p0 was 123 before entering the second time, and after entering the function, it became 234. However, I did not carry out the assignment operation.


I added code for the subject and added a little pointer address output.

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

Some possible output:

p1 0x28cc64, p2 0x28cc5c
 after first insert, 123
 insert func, 234, 0x28cc44

Can I say this is a compiler problem? . . I just had a try with my classmates.
gcc 4.8.4The compiler has this problem, butgcc 5.1Then it can be output normally. For specific results, see:http://ideone.com/AAOGdcIn addition4.8.4This modification is also ok

Stu *inset(Stu *node, Stu& stu) // plus a &

The reason may be that there was a problem with the reference to the returned temporary variable, which was optimized in version 5.1.


Reorganize your thinking:
StartedStu *inset(Stu *node, Stu stu)This belongs to value passing, here’sstuIt’s just a temporary variable and then returnsnodePointed tostu, that is, the second parameter, the address of this temporary variable, is called againinsertFunction, still points to the address of the second parameter, that isp2. So it will be output234, andStu *inset(Stu *node, Stu& stu)This reference is passed, but it is different herestuIn the first call ismainFunctionalp1This example, the second call isp2. So there is no abnormality.
Therefore, it is best not to return references to temporary variables.


As forgcc 5.1The optimization of-may be a custom class or structure, itself as a reference, personal speculation. . . .