分段故障:11时打印动态数组 [英] Segmentation fault: 11 while printing dynamic arrays

查看:160
本文介绍了分段故障:11时打印动态数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  std :: vector< double> IPWeights; 

然后将它传递给一个引用引用的函数

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

然后在我的主函数中,我改变了我的数组内容后,我想打印它:

  int size_weights = IPWeights.size(); 

for(int i = 0; i {
std :: cout }

但在屏幕上我只看到分段错误11 >

其中引用看起来像:

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

感谢任何建议,
提前感谢。

解决方案

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



$ b

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

      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);
    // ...



I have a simple C++ code where I define a dynamic array as:

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".

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:

    std::vector<double> IPWeights;
    IPWeights.resize(size_you_need);
    

  • Call IPWeights.push_back() instead of assigning by index:

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

这篇关于分段故障:11时打印动态数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆