What will happen if in a C program you assign a value to an array element whose subscript exceeds the size of array?
[A].
The element will be set to 0.
[B].
The compiler would report an error.
[C].
The program may crash if some important data gets overwritten.
[D].
The array size would appropriately grow.
Answer: Option B
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.
Because in c language bound checking is performed by compiler array size always be given by programmer side.
Raj said:
(Wed, Sep 7, 2011 06:36:23 PM)
The code which I tried in turbo C is
#include<stdio.h>
int main()
{
int arr[3]={1,2,3};
arr[5]=6;
printf("%d",arr[5]);
return 0;
}
This program prints the output as 6.
Can anyone explain please ?
Vishwas said:
(Fri, Jan 6, 2012 09:59:16 AM)
For character array there is an indication of end of the string by null char, but in integer array there is no such end, if there is an free space at address arr[5] in RAM it will get allocated by value 6.