Challenge - 5 Problems
Pointer Arithmetic Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of pointer increment on array
What is the output of this C code snippet?
C
#include <stdio.h> int main() { int arr[] = {10, 20, 30, 40}; int *p = arr; p++; printf("%d\n", *p); return 0; }
Attempts:
2 left
💡 Hint
Incrementing a pointer moves it to the next element in the array.
✗ Incorrect
The pointer p initially points to arr[0] which is 10. After p++, it points to arr[1], which is 20. So, *p prints 20.
❓ Predict Output
intermediate2:00remaining
Pointer subtraction result
What is the output of this C code?
C
#include <stdio.h> int main() { int arr[] = {5, 10, 15, 20, 25}; int *p1 = &arr[4]; int *p2 = &arr[1]; printf("%td\n", p1 - p2); return 0; }
Attempts:
2 left
💡 Hint
Pointer subtraction gives the number of elements between them.
✗ Incorrect
p1 points to arr[4], p2 points to arr[1]. The difference is 4 - 1 = 3 elements.
🔧 Debug
advanced2:00remaining
Identify the error in pointer arithmetic
What error will this C code produce when compiled or run?
C
#include <stdio.h> int main() { int x = 10; int *p = &x; p = p + 2; printf("%d\n", *p); return 0; }
Attempts:
2 left
💡 Hint
Pointer arithmetic beyond allocated memory is unsafe.
✗ Incorrect
Adding 2 to pointer p moves it beyond the single int variable x. Dereferencing it causes undefined behavior, often a segmentation fault.
📝 Syntax
advanced2:00remaining
Which pointer arithmetic expression is valid?
Which of the following pointer arithmetic expressions is valid in C?
Attempts:
2 left
💡 Hint
Pointer subtraction between two pointers to the same array is allowed.
✗ Incorrect
You can subtract two pointers (p - p) to get the number of elements between them. Adding two pointers or multiplying/dividing pointers is invalid.
🚀 Application
expert3:00remaining
Calculate sum using pointer arithmetic
What is the output of this C program that sums array elements using pointer arithmetic?
C
#include <stdio.h> int main() { int arr[] = {1, 2, 3, 4, 5}; int *p = arr; int *end = arr + 5; int sum = 0; while (p < end) { sum += *p++; } printf("%d\n", sum); return 0; }
Attempts:
2 left
💡 Hint
Pointer p moves from start to end of array, adding each element.
✗ Incorrect
The loop adds all elements: 1+2+3+4+5 = 15. Pointer arithmetic is used to traverse the array.