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
发布于 2010-02-15 22:00:38
由于问题被标记为c++,因此我将重构为:
void Call_By_Test( mynode *& first ) // rest of code remains the same这传递了按引用传递,而不需要额外的解引用。所有建议将指针传递给指针(void Call_By_Test( mynode ** first ))的解决方案都在指针变量的指针中使用按值传递语义。虽然您可以在C++中做到这一点,但按引用传递更清晰。
发布于 2010-02-15 21:52:25
答案是您没有使用按引用传递。你通过值来传递一个指针--这不是一回事。这意味着您将看到指针引用的数据发生了变化,但是在Call_By_Test方法中更改first本身的值不会产生任何影响。
发布于 2010-02-15 21:53:20
在函数中
void Call_By_Test(mynode * first)first实际上是函数的局部变量。更改它不会更改程序其余部分的状态。您需要一个指向指针的引用或指向指针的指针:
void Call_By_Test(mynode ** first)
{
free((*first)->next);
(*first)->next = NULL;
free(*first);
*first = NULL;
}并将其称为:
Call_By_Test( & first );https://stackoverflow.com/questions/2266317
复制相似问题