Reputation: 817
I can't understand why I get the run time error:
the variable ia is being used without being initialized.
However, as far as I can see, I have initialized it.
#include <iostream>
using namespace std;
int main()
{
//array dimensions
const int row_size = 2;
const int col_size = 4;
//array definition
int ia[row_size][col_size] = {{0, 1, 2, 3},{5, 6, 7, 8}};
cout << ia[2][4];
system("PAUSE");
return 0;
}
Upvotes: 0
Views: 132
Reputation: 27271
ia[2][4]
doesn't exist.
ia[0..1][0...3]
all exist, however.
Try:
cout << ia[1][3];
Arrays in C++ start with the index 0
. 1
is actually the 2
nd element. So:
int a[2] = {42, 50};
std::cout << a[0] << a[1]; // prints 4250
std::cout << a[2]; // a[2] doesn't exist!
Upvotes: 1
Reputation: 6116
Arrays are 0-based, i.e. the first element in an array a
is a[0]
. So the last element in an array of 4 elements would be a[3]
. In your case ia[1][3]
would give you the sought element I believe.
Upvotes: 0
Reputation: 21226
Array indexes start from 0, so your ia[2][4]
will be out of bounds. Should be ia[1][3]
.
Upvotes: 0
Reputation: 9926
C++ array indexes are zero-based. So to access the fourth column of the second row, you need to access ia[1][3]
.
Upvotes: 5