在C中,這樣的代碼:爲什麼局部變量可以是函數的返回值?
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int item;
struct node* next;
}Node;
Node * newNode(int i)
{
Node *x=malloc(sizeof(Node));
x->item=i;x->next=NULL;
return x;
}
int main()
{
int a=2;
Node *p=newNode(a);
printf("%d\n",p->item);
return 0;
}
功能newNode(INT)之後已經過去,指針X被釋放,然後指針p得到垃圾address.But結果爲2。請解釋這個過程。謝謝。
爲什麼不呢?返回的東西總是一個副本(即使它是一個C++引用,它本質上是一個指針的副本) –