[英]Segmentation fault: 11 while printing dynamic arrays
I have a simple C++ code where I define a dynamic array as: 我有一个简单的C ++代码,其中将动态数组定义为:
std::vector<double>IPWeights;
and then pass it to a function called reference with a reference (so I changed its content) like: 然后将其传递给具有引用的引用函数(因此我更改了其内容),如:
void reference (std::vector<double> &IPWeights)
and then in my main function, after I changed my arrays content I wanted to print it like: 然后在我的主要功能中,更改数组内容后,我希望将其打印为:
int size_weights=IPWeights.size();
for (int i=0; i<size_weights; i++)
{
std::cout<<IPWeights[i]<<std::endl;
}
but in the screen I only see "segmentation fault 11". 但在屏幕上,我仅看到“细分错误11”。
where the reference is simply looks like: 引用看起来像这样:
void reference( std::vector<double> &IPWeights)
{
IPWeights[0]=0.4500;
IPWeights[1]=0.2648;
IPWeights[2]=0.2648;
IPWeights[3]=0.2648;
IPWeights[4]=0.2519;
IPWeights[5]=0.2519;
IPWeights[6]=0.2519;
}
Any advice is appreciated, Thanks in advance. 任何建议表示赞赏,在此先感谢。
My crystal ball says that you don't allocate memory for the vector. 我的水晶球说您不为向量分配内存。 You should do one of the following:
您应该执行以下操作之一:
Initialize vector with appropriate size: 用适当的大小初始化向量:
std::vector<double> IPWeights(size_you_need);
Call IPWeights.resize()
before assigning to it: 在分配给
IPWeights.resize()
之前,先对其进行调用:
std::vector<double> IPWeights; IPWeights.resize(size_you_need);
Call IPWeights.push_back()
instead of assigning by index: 调用
IPWeights.push_back()
而不是通过索引分配:
IPWeights.push_back(0.4500); IPWeights.push_back(0.2648); //...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.