我正在尝试将一个指针数据复制到另一个指针,这样如果我更改一个指针,另一个指针中的值就不会改变。
我需要这个,因为我正在编写一个循环,其中有两个结构指针、value 和 lastValue。在循环的每次迭代中,我将 value
的内容分配给 lastValue
,并用新内容填充 value
。问题是因为两者都是结构指针,所以当我更改 value
时,lastValue
也会更改,这不是我想要的行为。代码应该是这样的(结构是来自 OpenCV 的 IplImages
):
IplImage *value;
Iplimage *lastValue;
while(1)
{
lastValue=value;
value=cvQueryFrame( capture );//This fills the struct with new information
}
如果它们位于普通结构中,这将起作用,但因为它们是指针,所以两者最终都具有相同的值。有没有办法获得指针的拷贝,具有相同的值,但地址不同?
最佳答案
value=cvQueryFrame( capture );
when I change value, lastValue changes too
不,它没有。如您所愿,指针 value
会被覆盖。这行代码不可能影响lastValue
。
but because they are pointers, both end up with the same value
不,它们是指针并不重要。指针本身仍然是对象。
但是,cvQueryFrame
返回一个指向缓冲区的指针,you shall not modify or free因为这是为您完成的:
Note that the image captured by the device is allocated/released by the capture function. There is no need to release it explicitly.
虽然the documentation有点不清楚,在我看来,缓冲区仅在下一次调用 cvQueryFrame
之前有效(然后将重新使用分配的内存)。因此,即使 lastValue
不能也不会改变,它还是会最终指向新的框架。
要解决这个问题,您可以显式复制 lastValue
指向的对象:
lastValue = cvCloneImage(value);
现在您可能会承担释放它的责任(但我粗略地浏览了文档,这还是不完全清楚):
cvReleaseImage(&lastValue);
关于c++ - 如何制作指针的拷贝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9149294/