C++ 请帮助我理解上面的代码行为;双空指针操作
大家好,请花点时间@查看下面的代码片段:C++ 请帮助我理解上面的代码行为;双空指针操作,c++,casting,void-pointers,C++,Casting,Void Pointers,大家好,请花点时间@查看下面的代码片段: #include <iostream> #include <stdlib.h> using namespace std; int func2(void* ptr1) { cout << " IN Func2" << endl; if(ptr1) { //i freed this Pointer. free(ptr1); p
#include <iostream>
#include <stdlib.h>
using namespace std;
int func2(void* ptr1)
{
cout << " IN Func2" << endl;
if(ptr1)
{
//i freed this Pointer.
free(ptr1);
ptr1 = NULL;
cout << "PTR MADE NULL" << endl;
return 1;
}
}
int func(void** ptr1)
{
cout << " IN Func" << endl;
int *ptr2 = (int*)malloc(10*sizeof(int));
if(ptr1)
{
*ptr1 = ptr2;
cout << " NOT NULL" << endl;
return 1;
}
else
{
cout << " NULL " << endl;
return 0;
}
}
int main()
{
int res = 0;
void *ptr = NULL;
func((void**)&ptr);
res = func2((void*)ptr);
if(res)
{
//Expecting this to be updated with NULL.. surely not working
if(ptr)
{
//why I'm Coming here
cout << "Freeing Ptr for 2nd time " << endl;
free(ptr);
}
}
cin.get();
return 0;
}
#包括
#包括
使用名称空间std;
int func2(void*ptr1)
{
cout您需要将ptr
的地址传递给调整后的func2()
修改func2()
,使其像func()
一样工作:
请告诉我:什么是投票的标准?????问题?在正常情况下,你不应该在C++中使用<代码>空洞*>代码>。
int func2(void** ptr1)
{
cout << " IN Func2" << endl;
if(*ptr1)
...
res = func2((void**)&ptr);