指针问题
好吧,我经历了 2 层函数 fun1 调用 func2 调用 func3 。 我基本上使用 int *ptr 一路向下传递指针,在调用堆栈的最低“级别”,我还有另一个为 int 数组动态分配内存的函数。 在顶层(func1 级别)我总是为传递的指针返回 null。 我已经追踪到 func3 并且分配的内存正在填充值,但是随着调用堆栈展开 func3 -> func2 指针突然消失(0x0000_0000)? 我在 func3 级别不明白,我基本上说 ptr = allocate_ptr_array,但从该返回值开始,它变为 NULL! 即使我没有释放内存,到底发生了什么? 我知道我的问题很令人困惑。 我已经在调试器中看到了这种情况的发生
Okay I go through 2 layers of functions fun1 calls func2 calls func3 . I pass a pointer all the way down using basically int *ptr, at the lowest "level" of the call stack I also have another function that dynamically allocates memory for an int array. At the top level (func1 level) I always get null back for the passed pointer. I have traced down to func3 and the allocated memory is being filled with values, but as the call stack unwinds func3 -> func2 suddenly the pointer just goes away (0x0000_0000)? I don't understand at func3 level I basically say ptr = allocate_ptr_array, but from that return it goes to NULL! Even though I didn't free the memory, what in the world is going on? I know my question is confusing. I have watched this happen in the debugger though
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
指针基本上是按值传递的。 您需要将指针传递给指针(int **p)以获取在外部函数中分配的内存。
}
The pointer is basically passed by value. You need to pass pointer to pointer (int **p) to get the memory allocated back in outer function.
}
用一些代码来阐明 aJ(完全正确)的答案:
To illuminate aJ's (completely correct) answer with some code:
这是一个很好的例子,供其他人将来参考。 实施后这是有意义的,感谢这些人。
Here is a good example for future reference bye other people. It makes sense after implementation and thanks to these guys.