main()使用参数参数First Node调用Call_By_Test()函数。
我在Call_By_Test()中释放了第一个节点,但是在main()中没有释放第一个节点地址,为什么?

typedef struct LinkList{
int data;
struct LinkList *next;
}mynode;

void Call_By_Test(mynode * first)
{
        free(first->next);
        first->next = (mynode *)NULL;
        free(first);
        first = (mynode *)NULL;
}
int main()
{
mynode *first;

first = (mynode *)malloc(sizeof(mynode));
first->data = 10;
first->next = (mynode *)NULL;

cout<<"\n first pointer value before free"<<first<<endl;

Call_By_Test(first);
// we freed first pointer in Call_By_Test(), it should be NULL
if(first != NULL)
        cout<< " I have freed first NODE in Call-By-Test(), but  why first node pointer has the value "<<first<<endl;


}

输出:
第一个指针值0x804b008
我已经在Call-By-Test()中释放了第一个节点,但是为什么第一个节点指针的值为0x804b008

最佳答案

由于该问题被标记为c++,因此我将重构为:

void Call_By_Test( mynode *& first ) // rest of code remains the same

这传达了传递引用而没有额外的取消引用。提议将指针传递给指针(void Call_By_Test( mynode ** first ))的所有解决方案都在指向指针变量的指针中使用值传递语义。尽管您可以在C++中执行此操作,但通过引用传递更为清晰。

关于c++ - 关于电话咨询的问题?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2266317/

10-11 23:57
查看更多