如何在运行时将指针设置为 Null (C++)
现在我有一个指针设置为二维数组中的一行。我希望该指针停止指向该行,但稍后我将使用该指针来做其他事情。我只想知道如何在初始化并指向一行后取消设置指针。
double* tempRow;
tempRow = (double*) malloc(size * sizeof(double));
...
tempRow = NULL;
不会取消 tempRow 变量与数组行的链接。为什么不呢?
我想知道我是否应该使用 C 语言。使用向量时会产生开销吗?
Right now I have a pointer set to a row in my 2D array. I want that pointer to stop pointing to that row, but I will be using the pointer later for something else. I just want to know how to unset the pointer after it is initialized and has pointed to a row.
double* tempRow;
tempRow = (double*) malloc(size * sizeof(double));
...
tempRow = NULL;
doesn't unlink the tempRow variable from the array row. Why not?
I wonder if I should be using C then instead. Will there be overhead when using a vector?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
虽然您已编写将 tempRow 设置为 NULL,但它不会释放您分配的内存。为此,您需要
但是,如果您按照标签建议使用 C++,则最好使用 C++ new/delete,
您甚至可以使用 STL 来为您处理内存分配。
尝试将 tempRow 指针重用于不相关的内容可能也没有必要。只需创建一个具有不同名称的新指针即可。在多个不同的不相关目的中重复使用变量可能会使代码以后很难理解。
While you have written will set tempRow to NULL, it wont release the memory you have allocated. For that you need
However if you're using C++ as the tags suggest, you'd be better off using C++ new/delete
you can even use the STL to handle your memory allocation for you.
Also trying to reuse the tempRow pointer for something unrelated is probably not necessary. Just create a new pointer with a different name. Reusing a variable form multiple different unrelated purposes can make code very hard to understand later.
我也是 C++ 新手,但不久前,有人告诉我,使用 std::vector 是处理数据数组的更安全的方法。
#include
中的内容一起使用的迭代器。.at(index)
元素访问进行边界保护。operator[]
进行 C 数组样式访问。你可以像这样声明一个向量:
I'm new at C++ as well, but a while ago, someone told me that using
std::vector
is a much safer approach to handling arrays of data.#include <algorithm>
..at(index)
element access.operator[]
.You would declare a vector like this:
您展示的示例应该可以工作。
此外,如果您在创建
temRow
NULL
之前没有释放内存,则 <强>内存泄漏。The example you've shown should work.
Also if you've not freed the memory before making
temRow
NULL
, you are leaking memory.这是最糟糕的投诉,也是解决方案提供商的噩梦。
你的意思是你得到编译错误?
如果是,您是否包含
?
和using namespace std;
That's the worst complaint and a solution providers's nightmare.
Do you mean you get a compilation error?
If yes, did you include
<cstdio>?
andusing namespace std;
用什么方法不行呢?在 C++ 中“取消设置”指针的正常方法是:
但是假设您已包含正确的标头或以其他方式对
NULL
有正确的定义,那么您所拥有的应该没问题。顺便说一句,在丢失指针之前,您应该首先在该内存上调用
free()
,否则会出现内存泄漏(假设您有充分的理由使用 C 风格 < code>malloc/free 而不是更 kosher C++new/delete
)。Doesn't work in what way? The normal way to "unset" a pointer in C++ is with:
but what you have should be fine, assuming you've included the correct headers or otherwise have the correct definition for
NULL
.As an aside, you should first call
free()
on that memory before losing the pointer, otherwise you'l have a memory leak (and this is assuming you have a good reason to use C-stylemalloc/free
instead of the more kosher C++new/delete
).