[英]Segmentation fault: 11 (C++ File input and output, classes and dynamic arrays)
[英]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.