Challenge your understanding of complex pointer manipulation, pointer arithmetic, and advanced memory access with this targeted quiz on pointer concepts in programming. Explore nuanced behaviors, address calculations, and practical use-cases for pointers in different scenarios.
Given an integer array int arr[5] = {10, 20, 30, 40, 50}; and a pointer int *p = arr;, what is the value of *(p + 2) after this assignment?
Explanation: Adding 2 to the pointer p moves it two integer positions forward, pointing to arr[2], which is 30. Option '20' is incorrect because that's arr[1], not arr[2]. Option '40' is arr[3], and '50' is arr[4]. The correct answer is 30 because pointer arithmetic advances to the actual array element by counting types, not bytes.
For a char array char buf[10];, what will (buf + 8) - buf evaluate to in C?
Explanation: Pointer subtraction returns the number of elements, not bytes, between the two pointers. (buf + 8) points to the ninth element and buf points to the first; their difference is 8. Option '10' is the array size, not the offset. '1' would be correct if the pointers were just one apart, and '9' if referencing the last element, but 8 is the correct result here.
If int x = 11;, int *p = u0026x;, and int **pp = u0026p;, what will **pp return?
Explanation: **pp dereferences first to get p, then again to obtain x's value, which is 11. 'u0026x' and 'u0026p' represent addresses, not the value itself. Option 'p' yields the pointer—not the stored integer. The correct answer is '11' since double indirection yields x's value.
If int arr[3] = {1,2,3}; int *p1 = arr; int *p2 = arr + 1; and you compute p2 - p1, what is the result?
Explanation: Pointer subtraction gives the number of elements between p2 and p1. Since p2 is one element ahead of p1, p2 - p1 equals 1. '2' would be true if p2 pointed two elements ahead, '3' matches the length of the array, and '0' would indicate the same address. The only correct count is 1 for these pointers.
Assuming void foo() and void (*fptr)() are declared, which statement correctly assigns the function address to the pointer?
Explanation: Assigning fptr = foo; correctly assigns the address of the function to the pointer. 'fptr = u0026foo();' uses parentheses, resulting in a call to foo instead of assignment. 'fptr = *foo;' is invalid syntax, and 'fptr = foo();' calls the function and assigns void to the pointer, which is incorrect. The first option is the proper and most common form.