2017-01-01 32 views
-4

我是編程新手,我試圖編寫一個從列表中獲取最短字符串的函數,但每次運行它時,Visual Studio都會顯示錯誤「拋出的異常:讀取訪問衝突」。錯誤在哪裏?C++爲什麼我的程序拋出異常?

#include <iostream> 
#include <string> 
using namespace std; 

const string &shortest_string(initializer_list<string> strings) { 
    string *shortest_one = nullptr; 
    for (string string : strings) { 
     if (shortest_one == nullptr) shortest_one = &string; 
     else { 
      if (string.size() < shortest_one->size()) shortest_one = &string; 
     } 
    } 
    return *shortest_one; 
} 

int main() { 
    cout << shortest_string({ "hello" , "my", "name", "is", "dan" }) << endl; 
    return 0; 
} 
+2

因爲'string string:...'創建了一個臨時變量,它存在於循環的一個循環中並在下一個循環中被破壞。並且你正在使用它的指針(指向釋放內存) – myaut

+0

'if(shortest_one = nullptr)' - 你認爲這樣做了什麼? –

+0

所以,現在你已經問了第二個不同的問題,我們什麼時候才能看到真正的代碼展品的行爲? – IInspectable

回答

-1

您使用與類型名稱匹配的名稱(字符串變量,字符串類型?)創建變量。另外還有一個問題,就是你返回指向局部範圍的對象的指針。那是UB。使用迭代器,你的函數可以像這樣工作:

const string shortest_string(initializer_list<string> strings) { 
    if(!strings.size()) return string(); 
    auto shortest_one = strings.begin(); 
    for (auto it = shortest_one+1; it < strings.end(); it++ ) 
    { 
     shortest_one = (it->size()< shortest_one->size()) ? it : shortest_one; 
    } 

    return *shortest_one; 
} 
+1

我不知道誰downvotes沒有解釋什麼是錯的答案。 – Swift

+1
+0

@IInspectable哦,萬一空列表我同意,整個功能應該短路返回空,是的。如果給定非法數據或產生錯誤,或者返回空結果,函數應該會崩潰,這是一個問題。對於隨機訪問迭代器,'it Swift

1

if (shortest_one = nullptr)不是比較操作。這是轉讓,即設置shortest_onenullptr。此操作評估爲0,因此if表達式等效於if (0)if (false)

然後在else塊,您正在使用shortest_one->size()shortest_one是空...

嘗試使用if (shortest_one == nullptr)代替。

+0

仍然收到錯誤。 – Pinwar78

+0

@ Pinwar78:不要責怪回答者。通過提供真實的代碼和解釋,提出一個真正的問題,哪一行產生訪問衝突。調用堆棧也有幫助。 – IInspectable

+0

@ Pinwar78你得到的錯誤是什麼? – nrofis

相關問題