+ 2

C++ Simple Array Addition

I wanted the program to write it down the calculation, but a very large number just popped up and I don't understand the logic behind it: #include <iostream> using namespace std; int main() { int arr[] = {1, 2, 3, 4,5}; int sum = 0; for (int x = 0; x < 5; x++) { sum += arr[x]; cout<< sum << " + " << arr[x+1] << "="; } cout << sum; return 0; } //Outputs: 1 + 2=3 + 3=6 + 4=10 + 5=15 + 32766=15 Can someone tell me where do I get the 32766 from?

22nd Jun 2020, 1:14 PM
fergoka
fergoka - avatar
6 odpowiedzi
+ 5
The variable x in the loop gets bigger than the array size (x becomes 4 in the last iteration and you go to arr[5] which doesn't exist), and so you point to a variable that isn't inside of the array. The new variable is some random number in memory, and each time you will run your program you will get a new random result (probably).
22nd Jun 2020, 1:20 PM
Mohamad Kamar
Mohamad Kamar - avatar
+ 3
Note what happens when x == 4: cout << sum << " + " << arr[4 + 1] ... You are accessing arr[5] which does not exist and is past the array boundary. So you get a random garbage value instead.
22nd Jun 2020, 1:21 PM
Schindlabua
Schindlabua - avatar
+ 3
fergoka Most programming languages will throw an error in such a case but not C/C++ :) It's a feature, not a bug. C and C++ sacrifice safety for control and speed. Checking array boundaries on every access would take extra time so we don't do it. So you end up reading past the array in memory and you get to read what the last process wrote there. (or whoever owned that piece of memory before)
22nd Jun 2020, 2:56 PM
Schindlabua
Schindlabua - avatar
+ 3
Exactly what Schindlabua said. In addition, when it comes to other languages like java/python, arrays are actually objects with attributes. So when you try to access an element that doesn't exist in the Object's context, it will give an error. Whereas in C/C++, arrays are simply stated as "continuous chunk of memory with the element is of specific size". So if you try to reach the element, you'l end up reaching whatever chunk of memory you encounter next..
22nd Jun 2020, 3:01 PM
Mohamad Kamar
Mohamad Kamar - avatar
+ 2
since the size of an array is 5 so there are only 5 elements in an array. Now look at the line which says cout<< sum << " + " << arr[x+1] << "="; here at i =4 you will get arr[5] which is out of range so the compiler is giving you a garbage value but sometime it also give an error of segmentation fault.
22nd Jun 2020, 4:58 PM
Abhishek Dimri
Abhishek Dimri - avatar
+ 1
Thanks a lot @Mohamad Kamar and @Schindlabua. It took me a few seconds to get what you are talking about. But the condition of for loop, shouldn't prohibit to access a value of a non-existent array??
22nd Jun 2020, 2:51 PM
fergoka
fergoka - avatar