请帮助我理解上述代码行为。了解 void 指针和双 void 指针操作
Please help me in understanding the above code behaviour.Understanding Void Pointers & double void Pointer Manipulation
大家好,请花点时间@查看下面的代码片段:
#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;
}
请帮助我理解以上代码行为。我更感兴趣的部分是"为什么ptr指针没有被分配NULL值&它用于第二次释放内存"
我的观察:
- void*ptr=NULL;在主要情况下,我将此指针指定为NULL。Ptr指向位置0x0。Ptr的地址是0x28ff40
- func((void**)&ptr);我用双指针打字在func()中{我动态地分配一些内存。因此Ptr指向某个地址,即0x7e36d8
} - func2(void*ptr1)这里我感到困惑:当我打印ptr时:它给我的是0x7e36d8,而不是0x28ff40所以当我使ptr=NULL时;位置处的内容为NULL,而不是@0x28ff40
第一个问题:如果内容@location 0x28ff40=NULL,我应该修改什么第二个问题:我搞砸了打字,我不明白我是怎么错过了基本地址的:0x28ff40
请帮助我理解这一点。
注意:请忽略返回值验证。请忽略C/C++风格混合使用的情况。不要建议更改函数Argument。
提前感谢大家!!!
您需要将ptr
的地址传递给调整后的func2()
。
修改func2()
以类似func()
:
int func2(void** ptr1)
{
cout << " IN Func2" << endl;
if(*ptr1)
...
然后这样称呼它:
res = func2((void**)&ptr);
相关文章:
- 引用一个已擦除类型(void*)的指针
- 如何将指针从一个void函数传递到另一个C++
- 指针没有更新它在void函数内部指向的值
- 错误:在为指针赋值时,void值没有被忽略
- 为什么我们要为avl树实现返回一个指向节点的指针,而不是void函数
- 如何在 C++ 中将 void 函数传递给 void 指针
- 将通用引用强制转换为可调用的 void 指针,反之亦然
- C++为 void 指针分配一个字符串
- 为什么在将 void 指针转换为整数指针时出现分段错误
- 当我使用 void 函数的返回值(通过强制转换函数指针)时,究竟会发生什么?
- 调用向量的函数,给定向量的指针作为 void *
- 取消引用 void 指针以将值分配给结构
- 为什么新表达式可以正确生成指针类型,即使它应该返回 void*?
- C 与 C++,处理 void** 指针
- reinterpret_cast指向 void(*&)() 的成员函数指针
- 使用 void 指针:void **ptr.. 如何修改共享内存的值?
- 我可以将函数指针 void* 强制转换为 std::function 吗?
- void*不是一个指向对象类型的指针 - void **的铸造错误
- 如何使用空指针(void*)
- 指针(void指针)和函数有一点混淆