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?
The element will be set to 0.
The compiler would report an error.
The program may crash if some important data gets overwritten.
The array size would appropriately grow.
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 1 of 3.

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.
(1)

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.
(1)

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)

Difu said:   1 decade ago
#include<stdio.h>
#define SQR(x) (x*x)
int main(){
int a,b=3;
a= SQR(b+2);
printf("%d",a);
return 0;
}

What is the output of this program? why not 25?

Subhakar said:   5 years ago
@ALL.

C compiler doesn't do bounds checking.

Rama said:   8 years ago
Why we don't do this program in java?

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.

Amertarasu said:   9 years ago
Isn't in the case why ArrayIndexOutOfBounds Exception exists?

Haritha said:   9 years ago
I tried it in linux compiler it gave the output as 10.

Manojkumar said:   1 decade ago
Very good.


Post your comments here:

Your comments will be displayed after verification.