C Programming - Arrays - Discussion
Discussion Forum : Arrays - General Questions (Q.No. 1)
1.
What will happen if in a C program you assign a value to an array element whose subscript exceeds the size of array?
Answer: Option
Explanation:
If the index of the array size is exceeded, the program will crash. Hence "option c" is the correct answer. But the modern compilers will take care of this kind of errors.
Example: Run the below program, it will crash in Windows (TurboC Compiler)
#include<stdio.h>
int main()
{
int arr[2];
arr[3]=10;
printf("%d",arr[3]);
return 0;
}
Since C is a compiler dependent language, it may give different outputs at different platforms. We have given the Turbo-C Compiler (Windows) output.
Please try the above programs in Windows (Turbo-C Compiler) and Linux (GCC Compiler), you will understand the difference better.
Discussion:
27 comments Page 3 of 3.
Amertarasu said:
9 years ago
Isn't in the case why ArrayIndexOutOfBounds Exception exists?
Anand kumar said:
9 years ago
I also tried and found no error, it still gave the expected output, no compilation or runtime error.
(1)
Priya said:
9 years ago
If the number of elements exceeds the array size, where the exceeded elements will be stored exactly.
For ex: If the array size is [5], if i enter six elements where the sixth element is stored. Whether it overwrites the array size or it stores some other location.
For ex: If the array size is [5], if i enter six elements where the sixth element is stored. Whether it overwrites the array size or it stores some other location.
Divya said:
8 years ago
On linux compiler will give some only warnings like array size is exceeded.and it will give o/p like this,
int a[2]={1,2,3,4,5};
o/p:1,2 only will give.
int a[2]={1,2,3,4,5};
o/p:1,2 only will give.
(1)
Rama said:
8 years ago
Why we don't do this program in java?
Subhakar said:
5 years ago
@ALL.
C compiler doesn't do bounds checking.
C compiler doesn't do bounds checking.
SB said:
5 years ago
When I tried it with GDB compiler, it gave the output 10.
#include<stdio.h>
int main()
{
int arr[2];
arr[3]=10;
printf("%d",arr[3]);
return 0;
}
10
Program finished with exit code 0.
#include<stdio.h>
int main()
{
int arr[2];
arr[3]=10;
printf("%d",arr[3]);
return 0;
}
10
Program finished with exit code 0.
(1)
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers