0

I am new to C++(please assume no C knowledge while answering). I have just started learning about arrays and ran the following code :-

#include<iostream>
using namespace std;

int main(){
    int arr_[10] ={1,2,3,4,5,6,7,8,9,0};
    int i=0;
    while (i<4)
    {
        printf("Value of arr_[ %i ] = %i \n",i ,arr_[i]);
        i++;
    }
    arr_[15] = 555;
    cout<<arr_[11]<<endl<<arr_[12]<<endl<<arr_[15];
    return 0;
}

I was expecting an error but to my surprise the program successfully compiled and ran to produce the following output :-

Value of arr_[ 0 ] = 648017456 
Value of arr_[ 1 ] = 648017456
Value of arr_[ 2 ] = 648017456
Value of arr_[ 3 ] = 648017456
4
1
555

I tried the same program once again on another machine . It produced a different output:-

Value of arr_[ 0 ] = 1 
Value of arr_[ 1 ] = 2 
Value of arr_[ 2 ] = 3 
Value of arr_[ 3 ] = 4 
-1644508256
0
555

So here are my queries I want to resolve :-

  1. If array size was fixed to 10 items how come I was able to add a value at the index number 15 ?

  2. If arrays are contiguous blocks of assigned memory , then how come I was able to jump out and declare a value skipping indices?

  3. From where do the output of values at index numbers 11 and 12 come from ?

  4. Does that mean C++ does not check ArrayOutOfIndex errors like Java and Python ?

  5. I later added following line to my code :-

    cout<<endl<<sizeof(arr_)/sizeof(int); //to find number of items

    which returned the number of Items in the array to be 10 . And this makes me horribly confused . I tried checking in books but could not find relevant information or the terminology is too verbose to understand as a beginner and on web hunting for such information proved to be too painful and went into vain.

Harsh
  • 15
  • 3
  • 2
    accessing an array out of bounds is [undefined behavior](https://en.wikipedia.org/wiki/Undefined_behavior). Anything could happen, and you see that with the different outputs on different machines. It's fruitless to try to understand why. – yano Oct 14 '21 at 14:32
  • C++ arrays are a bit of a mess. Basically an array is a pointer to the first object only and happily move on from there. They require you to do things correctly, you can just write beyond the address of the last value. It might be better to learn about std::array and std::vector first. – Pepijn Kramer Oct 14 '21 at 14:34
  • 2
    and `printf("Value of arr_[ %i ] = %i \n",i ,arr_)` is wrong, you forgot to access individual members with `[i]` – Stefan Riedel Oct 14 '21 at 14:34
  • "The built-in subscript expression `E1[E2]` is exactly identical to the expression `*(E1 + E2)`", the compiler will gladly let you shoot yourself in the foot if you want. But what you're doing is undefined behavior. – Mgetz Oct 14 '21 at 14:34
  • And I'm not sure I believe you anyway, are you sure you ran this _same_ code on both machines? As mentioned, `printf("Value of arr_[ %i ] = %i \n",i ,arr_);` should be `printf("Value of arr_[ %i ] = %i \n",i ,arr_[i]);`, can't imagine how you could get a `1 2 3 4` output on the other machine without that ... – yano Oct 14 '21 at 14:35
  • If it is any consolation, on my machine, the **undefined behavior** causes the program to crash. – Eljay Oct 14 '21 at 14:36
  • Thanks @StefanRiedel , I mistakenly deleted `[i]` while copy-pasting code from my editor. – Harsh Oct 14 '21 at 14:37
  • 2
    Answers. 1) developer's responsibility to not do that, 2) developer's responsibility to not do that, 3) **undefined behavior**, 4) correct: that's the developer's responsibility (C++ is not a nanny language, it gives you enough rope to shoot yourself in the foot), 5) not sure why you are confused here since the array has 10 elements. – Eljay Oct 14 '21 at 14:41
  • @PepijnKramer then saying that Arrays are contiguous (as many books and online sources list) is wrong I think . As such a behavior actually kills the very essence of saying so. – Harsh Oct 14 '21 at 14:41
  • @Eljay C++ is not a gospel . It maybe fault in design of the language or maybe it is left intentionally so for some purpose . And asking about it is important for anyone as such ignorance can lead to blunders in the real world . Also , due to this attitude of *Developer's responsibility is not to do so* and *Accept the way it is* actually leads to inefficient designs and a real hindrance for a beginner to learn . – Harsh Oct 14 '21 at 14:45
  • 2
    c++ has a core concept of you don't pay for what you don't need. Part of that is it does not waste cpu cycles checking for out of bounds conditions and leaves that up to the user. With that said if you instead had used `std::array myarray;` and use myarray.at(11) you would have had an exception thrown. [https://en.cppreference.com/w/cpp/container/array/at](https://en.cppreference.com/w/cpp/container/array/at) – drescherjm Oct 14 '21 at 14:47
  • *hindrance for a beginner to learn* Beginners in C++ should start with a [good C++ book](https://stackoverflow.com/a/388282/4641116). – Eljay Oct 14 '21 at 15:37

1 Answers1

2

When you try to access the out of bound element of the array then the output is undefined. That is why you are getting different results on different run of the program.

 arr_[15] = 555;
 cout<<arr_[11]<<endl<<arr_[12]<<endl<<arr_[15];

Both of the above statements produce undefined behavior.

You can read more on this topic at : Accessing an array out of bounds gives no error, why?

The program crashes here.

But here the program doesn't crash.

This is the result of undefined behavior.

Jason
  • 36,170
  • 5
  • 26
  • 60