简体   繁体   中英

Null poinnter exception with array in C++

I tried to learn basics for C++. Now I'm trying to figure out the arrays. But then i running this small program my IDE raise the null pointer exception.I didn't understand why this happend.

include <iostream>

using namespace std;

int main(){
int[] arr = {1, 2, 3};
for(int i=0; i < 4; i++){
  cout << arr[i] << endl;
}
exit 0;
}

I searched for answers on google about null pointer exception. I understand what it is, but don't understastand why it raised in my program. My array has 3 items, so the i<4 statement is correct in my opinion

The array has three elements, but you are trying to access the fourth one on the last iteration. The condition in the for loop is wrong. (Note: you can calculate the number of elements using sizeof arr / sizeof *arr or std::size(arr) , since C++ 17.)

int arr[] = {1, 2, 3}; 
for (int i = 0; i < 3; i++){
  std::cout << arr[i] << '\n';
}

To avoid this sort of issue altogether, use a range-based for loop .

for (const int& x : arr) {
    std::cout << x << '\n';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM