有关参考号码的问题?

SIV*_*IVA 1 c++ pass-by-reference argument-passing

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;


}
Run Code Online (Sandbox Code Playgroud)

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

Jon*_*eet 7

答案是你没有使用pass-by-reference.你是按值传递一个指针 - 这不是一回事.这意味着您将看到指针引用的数据中的更改,但first在Call_By_Test方法中更改其自身的值不会执行任何操作.


Dav*_*eas 5

由于问题标记为c ++,我将重构为:

void Call_By_Test( mynode *& first ) // rest of code remains the same
Run Code Online (Sandbox Code Playgroud)

这传达了传递参考而没有额外的解引用.建议将指针传递给指针(void Call_By_Test( mynode ** first ))的所有解决方案都在指向指针变量的指针中使用按值传递语义.虽然您可以在C++中执行此操作,但传递引用更清晰.