
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Accessing Array Out of Bounds in C/C++
In a language such as Java, an exception such as java.lang.ArrayIndexOutOfBoundsException may occur if an array is accessed out of bounds. But there is no such functionality in C and undefined behaviour may occur if an array is accessed out of bounds.
A program that demonstrates this in C is given as follows.
Example
#include <stdio.h> int main() { int arr[] = {1,2,3,4,5}; printf("The elements of array : "); for(int i = 0; i<6; i++) printf(" %d",arr[i]); return 0; }
Output
The output of the above program is as follows.
The elements of array : 1 2 3 4 5 32765
Now let us understand the above program.
The array arr has assigned values only till subscript 4. So when the array elements are printed, arr[5] results in a garbage value. The code snippet that shows this is as follows.
int arr[] = {1,2,3,4,5}; printf("The elements of array : "); for(int i = 0; i<6; i++) printf(" %d",arr[i]);
Advertisements