+ 1

If we exceed the 2d array size , what will be the output for it ?

for ex : i have an integer type array 'x'of 2 rows and 3 cols and i want to print the solution of x [2][0]. what will be the result of it ? will it give the garbage value or gives and error

13th Feb 2017, 2:52 AM
Mitul Pradhan
Mitul Pradhan - avatar
3 Respostas
+ 5
Index out of range. It will crashs your program on run time.
13th Feb 2017, 2:56 AM
Nahuel - avatar
But it gave me some different value.
13th Feb 2017, 2:59 AM
Mitul Pradhan
Mitul Pradhan - avatar
@Nahuel That's not actually correct in C++. It may crash your program at run time, but most likely will not. What it actually does is point to what is in memory beyond the end of the array and usually returns memory garbage. Take into account the following program in which we create an int array with a size of 10 and then initialize it in a for loop with the values 0-9. Then in the next for loop we output the values of that array going far beyond the end of the array returning garbage integer values from whatever it is that lies in memory beyond the end of the array. #include <iostream> using namespace std; int main() { int arr[10]; for (int i = 0; i < 10; ++i) { arr[i] = i; } for (int i = 0; i <= 20; ++i) { // 11 beyond end of array cout << "element " << i << " value " << arr[i] << endl; } return 0; } This program compiles and runs fine. This is because when you get values from an array you are really using a memory pointer and when you add to that pointer you move the pointer forward by 1. Think of memory as a row of boxes. Say we have 50 boxes and this array starts at box 7 and takes up boxes 7-16 (including) and other programs or the OS is using memory in the other boxes. As we move the pointer past the end of the array we start pointing at whatever those other programs have stored there. If we were to change these accidentally we could end up causing problems with the OS or those other programs. (It could also be stuff not in use that has just been left behind and not yet overwritten by any other process yet). The representation of this stuff in memory is what you're getting back.
13th Feb 2017, 3:50 AM
ChaoticDawg - avatar