Click here to Skip to main content
14,980,986 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
What happens when we try to access the element greater than the length of the array.
my input:1
output:1
Do we get the correct answer every time?

What I have tried:

C++
#include<stdio.h>
int main()
{
  int a[5];
  scanf("%d",&a[7]);
  printf("%d",a[7]);
  return 0;
}
Posted
Updated 26-Apr-21 20:09pm

Quote:
Do we get the correct answer every time?
Nope, you are getting the correct answer while you are lucky.
The result is 'unpredictable' and can make your program crash. See, for instance, Accessing array out of bounds in C/C++ - GeeksforGeeks[^].

By the way, why don't you read the C programming language specifications? The draft of the C17 standard is freely available (see C17 (C standard revision) - Wikipedia[^]).
   
v2
Depends on the rest of the code really, and on compiler options.

Sometimes - if you have the right compiler, and the right options - you will get an error, and your app will crash. But that's rare(ish) because it slows down every array access with bounds checking.

The more common problem is that other things in your application get corrupted, and your app fails to work correctly or even crash as a result.

Sometimes - as in your sample code - you won't notice a problem because the memory it does access is unused stack space.

And sometimes ... very unpredictable results will start happening ... :laugh:
   
CPallini is absolut correct but I add in debug build are some extra bytes around every array and you will get away with it but BUT in release build it will crash and you will have headaches and WON'T be able to reproduce it in the debugger.

Some mistakes are damned to be repeated from every generation ;-)
   
Quote:
Do we get the correct answer every time?

No, sometimes your program crash if your code hit a place you do not own.
If you own the place, you will get correct answer, but it will trash other variables which will make your program unpredictable.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900