十三誡增修--02:你不可以存取超過陣列既定範圍的空間
02. 你不可以存取超過陣列既定範圍的空間
錯誤例子:
int str[5];
for (int i = 0 ; i <= 5 ; i++) str[i] = i;
正確例子:
int str[5];
for (int i = 0; i < 5; i++) str[i] = i;
說明:宣告陣列時,所給的陣列元素個數值如果是 N, 那麼我們在後面
透過 [索引值] 存取其元素時,所能使用的索引值範圍是從 0 到 N-1
C/C++ 為了執行效率,並不會自動檢查陣列索引值是否超過陣列邊界,
我們要自己來確保不會越界。一旦越界,操作的不再是合法的空間,
將導致無法預期的後果。
備註:
C++11之後可以用Range-based for loop提取array、
vector(或是其他有提供正確.begin()和.end()的class)內的元素
可以確保提取的元素一定落在正確範圍內。
例:
// vector
std::vector<int> v = {0, 1, 2, 3, 4, 5};
for(const int &i : v) // access by const reference
std::cout << i << ' ';
std::cout << '\n';
// array
int a[] = {0, 1, 2, 3, 4, 5};
for(int n: a) // the initializer may be an array
std::cout << n << ' ';
std::cout << '\n';
補充資料:
http://en.cppreference.com/w/cpp/language/range-for
--
個人網頁:http://gnitnaw.github.io/
以後在C_and_CPP或LinuxDev發表的文章都會放一份在這邊。
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 86.209.153.222
※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1463058285.A.270.html
※ 編輯: wtchen (86.209.153.222), 05/12/2016 21:09:53
※ 編輯: wtchen (86.209.153.222), 05/12/2016 21:12:35
→
05/13 11:47, , 1F
05/13 11:47, 1F
→
05/13 11:48, , 2F
05/13 11:48, 2F
→
05/13 11:49, , 3F
05/13 11:49, 3F
推
05/13 11:56, , 4F
05/13 11:56, 4F
→
05/13 12:08, , 5F
05/13 12:08, 5F
→
05/13 16:12, , 6F
05/13 16:12, 6F
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章