[問題] 關於 array out of boundary 的例外處理

看板C_and_CPP (C/C++)作者 (小乖)時間16年前 (2009/04/17 22:37), 編輯推噓1(101)
留言2則, 1人參與, 最新討論串1/1
請問一下 我宣告了一個 array,做了 out of boundary 的存取 int num[10]; int* c = new int[10]; c[21] = 0; 我想利用例外處理的方式來自動幫我找出 out of array boundary 的錯誤 於是我寫了下列的 code 作測試 =================================================== #include <iostream> using namespace std; int main(int argc, char* argv[]) { int* c = new int[10]; try{ c[21]=9; }catch ( out_of_range ex ) { cerr << ex.what() << endl; exit( EXIT_FAILURE ); throw; }catch(...){ cerr << "caught other exception (non-compliant compiler?)\n"; throw; } return 0; } ==================================================== 初乎我想像的發現,對於 c[21] = 9 這樣的存取, out_of_range 攔截不到 我 google 了一下 http://www.java2s.com/Tutorial/Cpp/0280__STL-Introduction/0140__out_of_range-ex 是否 out_of_range 只適用於 std 函式庫 若是這樣的話,請問有什麼較好的方法可以利用 exception handling 的方式處理 out of boundary array 目前我是打算自己寫 throw eq. ================================================ int* c = new int[10]; try{ int n=21; if(n<10) c[n]=9; else{ throw "out of boundary"; } }catch(const char* str){ cerr << str << endl; } ================================================= -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 61.224.234.239

04/17 22:54, , 1F
用 std::vector 底下的 at()
04/17 22:54, 1F

04/17 22:54, , 2F
內建的陣列為了效率,不會幫你做這種檢查
04/17 22:54, 2F
文章代碼(AID): #19w9GDYh (C_and_CPP)
文章代碼(AID): #19w9GDYh (C_and_CPP)