What will be the output of the following code?#include <stdio.h>int main() { int arr[4] = {0, 1, 2, 3}; printf("%d\n", arr[-1]); return 0;}
Question
What will be the output of the following code?
#include <stdio.h>
int main() {
int arr[4] = {0, 1, 2, 3};
printf("%d\n", arr[-1]);
return 0;
}
Solution
The given C code attempts to access an array element using a negative index, specifically arr[-1]
. In C, array indexing starts at 0
, which means that valid indices for arr
(which has a size of 4) are 0
, 1
, 2
, and 3
. Accessing arr[-1]
results in undefined behavior because it is accessing memory outside the bounds of the declared array.
Explanation of Undefined Behavior:
-
Negative Indexing: C allows pointer arithmetic, and when using a negative index, it effectively moves the pointer backward from the base address of the array. Accessing
arr[-1]
may point to an invalid memory location, which is why this is considered undefined behavior. -
Possible Outputs: The output of running this code may vary depending on the memory state and how the compiler manages the array. The program may output garbage values, crash, or in some cases, it might even return a valid integer if that memory location can be interpreted correctly, but this is not guaranteed and not safe.
-
Best Practice: To avoid issues like this, it's essential to stay within the bounds of the array and only use valid indices.
Summary
In summary, the code resulted in an attempt to access an out-of-bounds array index, which leads to undefined behavior. Avoid negative indexing in C to ensure that your code runs correctly and predictably.
Similar Questions
What is the output for the following code?Note: This question helps in clearing conceptual technical interviews for service-based companies.
What will be the output of the following C code?#include <stdio.h>int main() { int i; for (i = 0; i < 5; i++); printf("%d\n", i); return 0;}
What will be the output of the following Pseudocode?int c = 0, d = 0 while ( d< 6 ) d=d+2 c=c+1 end while loop print c3564
What will be the output of the following code snippet?var a = 1; var b = 0; while (a <= 3) { a++; b += a * 2; print(b); }*4 10 181 2 3None of Above1 4 7
What is the output of the following code snippet?int x = 5;int y = 2;int result = x % y;System.out.println(result);Question 2Answera.3b.2c.1d.0
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.