Reputation: 97
I've been reading up on some Dynamic Programming. It works (at least from my understanding) by generating a two-dimensional integer array to store solutions to subproblems.
In C++, you can declare a two-dimensional, 10x10 array like this: int d[10][10];
.
Now I thought by declaring the array without assigning any values, all the values in the array should be 0, however, the values in the array are a weird combination of large positive or negative numbers and zeros.
I have tried this piece of code here to test outcomes on different compilers:
#include<iostream>
using namespace std;
int main()
{
int d[10][10];
for (int i =0; i < 10; i++){
for (int j = 0; j < 10; j++){
cout << d[i][j] << " ";
}
cout << endl;
}
return 0;
}
Results:
cpp.sh
Test 1:
Test 2:
OnlineGDB
Test 1:
Test 2:
Visual Studio
Test 1:
Test 2:
As you can see, CPP.SH and OnlineGDB both generate seemingly arbitrary numbers in the place of some values while others are 0. The only exception being Visual Studio. Is there an explanation for where these seemingly arbitrary numbers come from? Why is Visual Studio the only compiler that doesn't have this kind of behavior? Thanks.
Upvotes: 0
Views: 946
Reputation: 359
There is no default value for int when declared as non static variable in most cases. That is why it is giving such random values. just use this int array[ROW][COLUMN]={0};
It will give the output that you are looking for.
Upvotes: 0
Reputation: 9678
Because the memory has not yet been initialised, so you are seeing whatever values happen to be left in that memory. If you want to initialise to zero, you can do:
int d[10][10] {};
Upvotes: 1