[英]Segmentation fault (core dumped) - C++ Error
我正在嘗試編寫一個簡單的矢量加法代碼,但出現此錯誤。 我不知道那是什么。 我在 Ubuntu 18.04 中使用 VS Code。
int main(){
std::vector<int> vect1 = {1,2,3,4,5};
std::vector<int> vect2 = {6,7,8,9,10};
std::vector<int> vectsum;
for (int i = 0; i < vect1.size(); i++){
std::cout << vect1[i] << " ";
}
std::cout << std::endl;
for (int j = 0; j < vect2.size(); j++){
std::cout << vect2[j] << " ";
}
for(int i = 0; i < vect1.size(); i++){
vectsum[i] = vect1[i] + vect2[i];
}
for (int i = 0; i < vectsum.size(); i++){
std::cout << vectsum[i] << " ";
}
return 0;
}
Output:
1 2 3 4 5
Segmentation fault (core dumped)
您還沒有為 vectsum 分配任何 memory (因此,當您為其中一個元素賦值時,您遇到了 NULL 指針)
std::vector<int> vectsum(5);
在行vectsum[i] = vect1[i] + vect2[i];
您不會通過為容器添加下標來向vectsum
添加元素。 您正在嘗試訪問 memory 的未分配區域。
一個簡單的解決方案可以是以下形式:
for(int i = 0; i < vect1.size(); i++){
// Allocate memory as needed
vectsum.push_back(vect1[i] + vect2[i]);
}
使用下標時還應考慮以下警告:
warning: comparison of integer expressions of different signedness:
‘int’ and ‘std::vector<int>::size_type’ {aka ‘long unsigned int’}
這告訴您不要混合使用有符號和無符號類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.