Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
210 views
in Technique[技术] by (71.8m points)

c++ - Segmentation fault: 11 while printing dynamic arrays

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...