what if the 1st element is the biggest amongst all and for the subarrays. currentsum=cumSum[0]-cumSum[-1] and how can we fetch cumSum[-1] here its an vague value.
Doubt on statement currentsum=cumsum[j]-cumsum[i-1];
as negative indexing isn’t allowed in c++.
when we do int a[ ]={1,2,3,4,5 }; cout<<a[-1]; Output is: (some garbage value) and when we do int a[5]={0}; cout<<a[-1]; Output is : 0 why is it so? as negative indexing isn’t allowed in C++.
Yes you are correct but with the new compilers, it works. But still you should prevent negative indexes in c++ because of uncertain behavior .
@Pratyush Kumar, my question was why is it so? as i haven’t initialized any value to a[-1] in any of the code
There is no such theory for negative indexes in c++…Negative indexes show uncertain behavior in C++… so giving an exact answer for your question is not possible. Just you can run and see how your code responds for different negative indexes.
Also for this https://ide.codingblocks.com/s/205187
a[-1] is giving garbage value. If you seperatly initialize a[-1] with 0 or so…then it always show the value assigned to it.
What you should be aware of is as follows:
In C/C++, the element a[i] just means go to the ith element starting from the base address of array a.
So, a[0] means the base address of a itself. a[1] means the address that immediately follows the base address. And so on…
For simplicity, assume that an int takes only 1 byte and that the base address of a is 1000. So, a[0] is the element in address 1000, a[1] is the element in the address 1001, …, a[57] is the element in the address 1057, and so on… Definitely, a[i] means element in the address 1000 + i.
So, a[-1] means the element in the address 1000 + -1, which is element in the address 999.
In other words, the integer, that precedes even the first element of the array.
Now, there are two cases that can arise:
- The above said location is restricted for access. Then, we get a Runtime Error (Segmentation Fault).
- No restriction for access. The element at that address can be read from or written into. However, this kind of behaviour is clearly undefined, as to we don’t know what exactly is getting stored in that location.
If we specifically know what is there in that location, it is ok. But in the other case, behavior is uncertain.
You can also refer this https://stackoverflow.com/questions/47170740/c-negative-array-index