ProgrammingHardWipro · Cognizant pattern
What can be said about this program?
What can be said about this program?
int main(void) {
int arr[5];
arr[5] = 10;
printf("%d", arr[5]);
}- A. It is well-defined and simply writes past the array into adjacent padding bytes
- B. Accessing arr[5] is undefined behavior: valid indices for arr are 0-4, so the program may print 10, corrupt other data, or crash
- C. It is a compile-time error because the array bound is known at compile time
- D. It always prints 0 because C zero-fills memory just past an array
Correct answer: B. Accessing arr[5] is undefined behavior: valid indices for arr are 0-4, so the program may print 10, corrupt other data, or crash
arr has 5 elements, indices 0 through 4; arr[5] is out of bounds. Out-of-bounds array access is undefined behavior with no guaranteed outcome, even if no immediate crash is observed.
More C Programming questions
- What is the only output consistent with the C standard? c int a[3] = {10, 20, 30}; int p = a; printf("%d %d", p++, p);
- What is printed? c int x = 5; x = x++ + 1; printf("%d", x);
- What is printed? c int i, j; for (i = 0, j = 10; i < 3; i++, j--) ; printf("%d %d", i, j);
- What is printed? Assume 32-bit int, two's complement. c unsigned int a = 5, b = 9; a = a ^ b; b = a ^ b; a = a ^ b; printf("%u %u", a, b);
- What is printed? c int flag = 0, mask = 2; flag |= mask == 2; printf("%d", flag);
- What is printed? c int a = 1, b = 2, c = 3; int arr[3] = {&a, &b, &c}; int p = arr; for (int i = 0; i < 3; i++) { (p + i) = 10; }…