Reputation: 67
I'm new to C++, and I've started to learn arrays. Here is my program on arrays:
#include <iostream>
using namespace std;
int main(){
int arr[3][3];
for (int i = 0; i<3; i++){
for (int j = 0; j<3; j++){
cout << "Enter " << j + 1 << " element of " << i + 1 << " row:";
cin >> arr[i][j];
}
}
for (int i = 0; i<3; i++){
for (int j = 0; j<3; j++){
cout << j + 1 << " element of " << i + 1 << "row:";
cout << arr[i][j] << endl;
}
}
system("pause");
return 0;
}
I know that array's first index in C++ is zero. So, logically, an array arr[3][3]
should have 4 * 4 = 16 elements, right? But practically, if I change 3 to 4 in my for
cycles, I'll get out of range error. Why does it happen? Am I missing something?
So, how much elemets are in arr[3][3]?
Upvotes: 0
Views: 85
Reputation: 2033
I know that array's first index in C++ is zero.
You are correct.
So, logicaly, an array arr[3][3]should have 4 * 4 = 16 elements, right?
Since first index is 0, arr[3][3] will be 0,1,2 rows and 0,1,2 columns. So, 9 elements
Check out this link for tutorials on array (or C++ in general ☺ )
http://www.cplusplus.com/doc/tutorial/arrays/
Upvotes: 1
Reputation: 206737
So, logically, an array
arr[3][3]
should have4 * 4 = 16
elements, right?
That is not correct.
For
int arr[3];
the valid element range is arr[0]
- arr[2]
. There are 3 elements.
For
int arr[3][3];
the valid element range is arr[0][0]
- arr[2][2]
. There are 9 elements.
Upvotes: 1
Reputation:
When you declare an array, you write the number of elements(not counting 0, int arr[3]
is an array with 3 elements. Only when you use them, you start counting from 0 (arr[2] = 666
accesses third element).
Upvotes: 1