Question 5
Back to Exercise
This program should print 15, the sum of the array. What does it print, and why?
#include <stdio.h>
int sum(int *a) {
int s = 0;
for (size_t i = 0; i < sizeof a / sizeof a[0]; i++)
s += a[i];
return s;
}
int main(void) {
int a[] = {1, 2, 3, 4, 5};
printf("%d\n", sum(a));
return 0;
}
- A It prints 15; the code is correct
- B It prints 3: inside sum(), sizeof a is the pointer size (8), so the loop runs only 2 times Correct
- C It prints 1: the loop runs once
- D It does not compile
Correct Answer: Option B
Inside sum(), a is a pointer: 8 / 4 = 2, so only a[0] + a[1] = 3 is added. Compilers warn about this pattern. Pass the length: int sum(const int *a, size_t n).
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!