返回指针值在从方法中脱颖而出后会更改
Return pointer value changes after passing out from a method
我使用Eigen
库中的代码有一个奇怪的行为。
如果我将指针分配给DoubleListCg->doubles
,则我获得的DoubleListCg->doubles[i]
的值是错误的。但是,如果我一一分配元素,那么我对上述指针数组的值是正确的。为什么?
这是我下面的代码:
#define DllExport __declspec( dllexport )
#include "stdafx.h"
#define EIGEN_USE_MKL_ALL
#include <iostream>
#include "Eigen/Dense"
#include "Eigen/src/Core/util/MKL_support.h"
#include <Eigen/Sparse>
#include <Eigen/Eigenvalues>
#include <vector>
#include <Eigen/PardisoSupport>
using namespace std;
using namespace Eigen;
extern "C" struct DllExport DoubleListCg
{
int num_points;
double* doubles;
};
// working
void DoubleList(VectorXd vector, DoubleListCg *dListPtr)
{
dListPtr->num_points = vector.size();
dListPtr->doubles= (double*) malloc ( dListPtr->num_points*sizeof(double));
for (int i = 0; i < vector.size(); i++)
{
dListPtr->doubles[i]=vector[i];
}
}
//not working
void DoubleList2(VectorXd vector, DoubleListCg *dList)
{
dList->num_points = vector.size();
dList->doubles =vector.data();
}
void VectorConvert()
{
VectorXd vector(3);
vector<<1,2,3;
DoubleListCg dList;
DoubleList(vector, &dList); //this works; the dList gets the right values at first element
DoubleListCg dList2;
DoubleList2(vector, &dList2) //this doesn't work; the dList2 gets the wrong values at first element
}
我挂断的一定是真正的基础。
相关问题:我是否可以将dList->doubles
指向vector.data()
?我不想一遍又一遍地复制所有内容
//not working
void DoubleList2(VectorXd vector, DoubleListCg *dList)
{
dList->num_points = vector.size();
dList->doubles =vector.data();
}
在上述函数中 vector
是局部变量函数 DoubleList2
。当功能返回或完成时,该局部变量将被破坏,dList->doubles
成为一个悬空的指针,如果访问了这种悬空的指针,则会导致不确定的行为。
正确的实现将是:
void DoubleList2(VectorXd vector, DoubleListCg *dList)
{
dList->num_points = vector.size();
dList->doubles = (double*) malloc ( dList->num_points*sizeof(double));
memcpy(dList->doubles, vector.data(), dList->num_points*sizeof(double));
}
void DoubleList(VectorXd vector, DoubleListCg *dListPtr)
vector
中是参数的(临时)副本。当您分配内存然后将值复制到其中时,它们将保留在dListPtr
中。在无工作的情况下,.data()
指针指向暂时分配的数组。当它不在范围内时,不能保证保证保留记忆。如果您通过引用传递vector
,则内存将保持分配,直到原始内容不超出范围。
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 通过方法访问结构
- 最小硬币更换问题(自上而下方法)
- C++为构建时间获取QDateTime的可靠方法
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 处理多个异常集合的C++方法
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 有什么方法可以遍历结构吗
- 当类在C++中定义时,有什么方法可以"register"类吗?
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- 使用std::函数映射对象方法
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- C++从另一个类访问公共静态向量的正确方法是什么
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 没有为自己的结构调用列表推回方法
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 在类定义之后定义一个私有方法
- 枚举环境变量的惯用C++14/C++17方法
- 返回指针值在从方法中脱颖而出后会更改