[英]Segmentation fault error C++
我正在編寫一個簡單的程序,將兩個向量交替進行,並將push_backs的向量轉換為第三個向量,但是我遇到了分段錯誤錯誤(內核已轉儲)。 我做了一些研究,似乎是我正在訪問不存在或不應該訪問的內存。 我知道這是一個簡單的修復程序,但是我對C ++還是很陌生,因此可以不勝感激。
vector<int> alternate(vector<int> a, vector<int> b)
{
int n = a.size();
int m = b.size();
vector<int> c(n + m);
int i;
for(i = 0; i < a.size() and i < b.size (); i++)
{
c.push_back(a[i]);
c.push_back(b[i]);
}
return c;
}
int main () {
vector<int> a,b,c;
int temp1;
int temp2;
while (temp1 != -1) {
cin >> temp1;
if(temp1 == -1) {
break;
}
a.push_back(temp1);
}
while (temp2 != -1) {
cin >> temp2;
if(temp2 == -1) {
break;
}
b.push_back(temp2);
}
c = alternate(a,b);
int i;
for(i = 0; i < c.size(); i++) {
cout << c[i] << endl;
}
}
據我所知,您在這里有兩個問題:
temp1
和temp2
,但沒有初始化它們,這是UB。 嘗試int temp1 = 0; int temp2 = 0;
int temp1 = 0; int temp2 = 0;
。 alternate
中,您將使用兩個輸入向量之和初始化返回向量,例如vector<int> c(n + m);
,然后使用push_back
添加這些輸入的元素。 這樣,您將在返回向量的開始處輸入n+m
零,然后在輸入元素處輸入零。 我很確定您不想要這個。 您不需要為向量設置默認大小,只需使用push_back
如果您堅持使用默認大小,則可以為向量的索引分配值。 您的代碼有一些問題,上面提到了一些問題。 最重要的問題如下:
其他較小的問題如下:
畢竟,結果應類似於以下內容:
#include <iostream>
#include <vector>
using namespace std;
vector<int> alternate(const vector<int>& a, const vector<int>& b)
{
const auto n = a.size();
const auto m = b.size();
const auto N = max(n, m);
vector<int> c;
c.reserve(n+m);
for(size_t i = 0; i < N; ++i)
{
if (i < n) c.push_back(a[i]);
if (i < m) c.push_back(b[i]);
}
return c;
}
int main () {
vector<int> a,b,c;
while (true) {
int temp;
cin >> temp;
if(temp == -1) {
break;
}
a.push_back(temp);
}
while (true) {
int temp;
cin >> temp;
if(temp == -1) {
break;
}
b.push_back(temp);
}
c = alternate(a,b);
for (auto val : c) {
cout << val << endl;
}
}
正如兩個答案所指出的,未初始化的變量以及使我的“ c”向量太大是罪魁禍首
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.