47.2k views
0 votes
What will happen if in a C program you assign a value to an array element whose subscript exceeds the size of the array?

a) Program terminates with an error
b) Value gets stored at the last index
c) Value gets stored at the first index
d) Nothing happens, the value is discarded

User Penger
by
7.2k points

1 Answer

5 votes

Final answer:

If you assign a value to an array element whose subscript exceeds the size of the array in a C program, it will result in undefined behavior. This can cause unpredictable results or crashing the program.

Step-by-step explanation:

If you assign a value to an array element whose subscript exceeds the size of the array in a C program, it will result in undefined behavior. This means that the program can exhibit unpredictable and inconsistent behavior. It may overwrite other variables or data in memory, causing unexpected results or crashing the program.

For example, consider an array int numbers[5]; with indexes 0 to 4. If you try to assign a value to numbers[5], it goes beyond the size of the array. The behavior of the program cannot be determined and can lead to potentially serious consequences.

To avoid this, it is crucial to ensure that array accesses stay within the bounds of the array, using indexes from 0 to (array_size - 1).

User CraftyB
by
7.8k points