Is it possible to access array[n]th element?

This code is not giving any error. How is it possible to access arr[n]th element?

int main(){

int n;

cin>>n;

int arr[n];

for(int i=1;i<=n;i++){

    cin>>arr[i];                           // at i=n, it will access arr[n]. How??

}



for(int i=1;i<=n;i++){

    cout<<arr[i]<<" ";

}



return 0;

}

There’s Undefined Behaviour for you :man_shrugging:

It gives an error if you use the right compiler flags:

[simon@simon-laptop][05:08:19]
[~/devel/hackerrank/otherpeoples]>./compile-latest-cpp.sh 
Compiling m_vaidya-blah2.cpp
Executing command:
  g++ -std=c++17 m_vaidya-blah2.cpp -O3 -g3 -Wall -Wextra -Wconversion -DONLINE_JUDGE -D_GLIBCXX_DEBUG    -fsanitize=undefined -ftrapv
Successful
[simon@simon-laptop][05:09:02]
[~/devel/hackerrank/otherpeoples]>echo "1
1" | ./a.out
m_vaidya-blah2.cpp:22:20: runtime error: index 1 out of bounds for type 'int [*]'

Hey, can you explain why you’ve used -O3 flag instead of -O2 flag?

No particular reason, to be honest :slight_smile:

1 Like

Okay :sweat_smile:

1 Like

actually it is possible because
int arr[n]; allocates the n contagious memory address starting with arr+0
so when you are taking arr[n] as input you are simply accessing the address arr+n and giving it some value. so when you access it simply prints the value you initialised it with.