ProgrammingVery hardProduct company OA
What is the behavior?
What is the behavior?
int arr[5] = {1,2,3,4,5};
int *p = arr + 5;
printf("%p", (void*)p);
printf("%d", *p);- A. Both the pointer formation and the dereference are well-defined, printing a[5]
- B. Forming arr+5 (one-past-the-end) is well-defined, but dereferencing it with *p is undefined behavior
- C. Both lines are undefined behavior
- D. Only the printf of the pointer is undefined, the dereference is fine
Correct answer: B. Forming arr+5 (one-past-the-end) is well-defined, but dereferencing it with *p is undefined behavior
C explicitly permits forming a pointer to one-past-the-end of an array (useful for loop bounds) without it being UB, but actually dereferencing that pointer (reading through it) IS undefined behavior, since there is no object there.
More C Programming questions
- What is the behavior? c char buf[5]; strcpy(buf, "hello world"); printf("%s", buf);
- What is the behavior? c int a = 10; int b = a << 32; printf("%d", b);
- What is the behavior? c const int x = 10; int p = (int)&x; p = 20; printf("%d", x);
- What is the behavior? c int a[3] = {1, 2, 3}; memcpy(a, a + 1, 2 sizeof(int)); printf("%d %d %d", a[0], a[1], a[2]);
- What is the behavior? c void f(int n) { char buf[n]; for (int i = 0; i <= n; i++) buf[i] = 'a'; } int main(void) { f(10); }
- What is printed? c // file1.c int x = 10; // file2.c (same program, separate translation unit) extern int x; void show(void) {…