Your program has undefined behavior because you're accessing elements outside the bounds of the array arr
.
When you wrote:
int arr[10][2]; //arr is a 2D array
The above statement defines a 2D array. This means, arr
has 10
elements and each of those 10
elements are themselves an array of 2
int
elements.
This also means that you can only access(safely) the elements:
arr[0][0] arr[0][1]
arr[1][0] arr[1][1]
arr[2][0] arr[2][1]
...
...
arr[9][0] arr[9][1]
And if you try to(which you do in your program inside for loop) access any other elements outside the above bounds, you'll get undefined behavior.
Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior.
So the output that you're seeing(maybe seeing) is a result of undefined behavior. And as i said don't rely on the output of a program that has UB.
So the first step to make the program correct would be to remove UB(in this case by making sure that index don't go out of bound). Then and only then you can start reasoning about the output of the program.
Solution 1
One alternative is to use std::vector
as shown below:
//create a 2D vector with 10 rows and 2 columns where each int element has value -1
std::vector<std::vector<int>> arr(10, std::vector<int>(2, -1));
Solution 2
You should consider using std::fill
instead of memset
:
std::fill(*arr, *arr + 10*2, -1);
1For a more technically accurate definition of undefined behavior see this where it is mentioned that: there are no restrictions on the behavior of the program.