2016-08-22 73 views
0

我正在編寫一個程序來分割任意兩個數字。問題是,每當我運行該程序,我得到一個錯誤,指出:獲取由信號SIGSEGV(地址邊界錯誤)終止的「./a.out」

「./a.out」通過信號SIGSEGV終止(地址邊界錯誤)

而且這個錯誤發生在線路:

a = std::stoi(temp_vec.front()); 
b = std::stoi(temp_vec.back()); 

c = std::stoi(temp_vec.front()); 
d = std::stoi(temp_vec.back()); 

這是我的計劃:

#include <iostream> 
#include <string> 
#include <vector> 

void split_number(std::vector<std::string> vect, int x); 

int main() 
{ 
    int x = 0, y = 0, a = 0, b = 0, c = 0, d = 0; 
    std::vector<std::string> temp_vec; 

    std::cout << "Enter x: "; 
    std::cin >> x; 
    std::cout << "Enter y: "; 
    std::cin >> y; 

    split_number(temp_vec, x); 
    a = std::stoi(temp_vec.front()); 
    b = std::stoi(temp_vec.back()); 

    split_number(temp_vec, y); 
    c = std::stoi(temp_vec.front()); 
    d = std::stoi(temp_vec.back()); 

    return 0; 
} 

void split_number(std::vector<std::string> vect, int x) 
{ 
    vect.clear(); 

    //1. convert x to string 
    std::string temp_str = std::to_string(x); 

    //2. calculate length 
    std::size_t len = temp_str.length(); 
    std::size_t delm = 0; 
    if(len % 2 == 0) { 
    delm = len/2; 
    } else { 
    delm = (len + 1)/2; 
    } 

    //3. populate vector 
    vect.push_back(temp_str.substr(0, delm)); 
    vect.push_back(temp_str.substr(delm + 1)); 
} 

任何幫助,將不勝感激。

回答

3

由於矢量是空的,所以會出現分段錯誤。您的向量爲空,因爲您將初始向量的副本傳遞給split_number()。由於split_number()的簽名表示需要副本,因此通過了該副本。將其更改爲:

void split_number(std::vector<std::string> & vect, int x) 

的符號,使vect參數引用參數,並修改調用代碼顯示。

相關問題