繁体   English   中英

分段错误:打印动态数组时为11

[英]Segmentation fault: 11 while printing dynamic arrays

我有一个简单的C ++代码,其中将动态数组定义为:

std::vector<double>IPWeights;

然后将其传递给具有引用的引用函数(因此我更改了其内容),如:

void reference (std::vector<double> &IPWeights)

然后在我的主要功能中,更改数组内容后,我希望将其打印为:

int size_weights=IPWeights.size();

for (int i=0; i<size_weights; i++)
{
    std::cout<<IPWeights[i]<<std::endl;
}

但在屏幕上,我仅看到“细分错误11”。

引用看起来像这样:

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;
}

任何建议表示赞赏,在此先感谢。

我的水晶球说您不为向量分配内存。 您应该执行以下操作之一:

  • 用适当的大小初始化向量:

     std::vector<double> IPWeights(size_you_need); 
  • 在分配给IPWeights.resize()之前,先对其进行调用:

     std::vector<double> IPWeights; IPWeights.resize(size_you_need); 
  • 调用IPWeights.push_back()而不是通过索引分配:

     IPWeights.push_back(0.4500); IPWeights.push_back(0.2648); //... 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM