Reputation: 389
Trying to learn c++, I wrote the following code but don't understand why its not:
int arrNum[2][2]
instead of
int arrNum[3][3]
I thought the array started at zero, so I have two height, two length - if you start at zero, right?
int main()
{
int arrNum[3][3] = {
{0,5,7},
{1,5,7},
{2,5,7}
};
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
cout << arrNum[i][j] << " ";
}
cout << endl;
}
return 0;
}
Upvotes: 2
Views: 110
Reputation: 2982
C/C++ feature zero based indexing. This means that an array's first element is at index zero. It also means that the size of the array is the index of the last element plus one. This holds for any array type, not just multidimensional.
When declaring an array you must state its size inside square brackets []
. For example, in the following code:
int arrA[2][2];
arrA
is a multidimensional array of size 2 in each dimension. Therefore, in each dimension, the element indexes are 0
and 1
. Note that they go from 0
to the size of each dimension minus 1. You would access each element as:
arrA[0][0];
arrA[0][1];
arrA[1][0];
arrA[1][1];
It's the same for one-dimensional arrays such as:
int arrB[2];
It is of size 2 and its elements are accessed as:
arrB[0];
arrB[1];
Upvotes: 1
Reputation: 1382
Yes, array indexing are started from 0. But the size is not.
int arrNum[2][2]
It means 2 element sized array of 2 element sized array integer.
Upvotes: 0
Reputation:
Sizes of arrays start as 1. Indexing, on the other hand, start at 0.
So, let's say you have an array (any array):
int arr[2] = {0,1};
Here, the size is 2, and it is the size that goes in these original []
brackets.
On the other hand, if you want to access an array after you have created it, you do so like this:
std::cout << arr[0]; // ouputs 0
std::cout << arr[1]; // outputs 1
std::cout << arr[2]; // will, among other things, probably crash your program as there
// are only 2 items in the array, but accessing started counting at 0
So, in short, when you access arrays, you start at 0. But when you declare them, you give the actual size, which would start counting at 1.
Upvotes: 1