Implement sum_array so it returns the sum of exactly length elements. The caller owns the array; handle a null pointer or zero length without dereferencing it.
Requirements
Do not read past length
Return 0 for NULL or length 0
Use size_t for the element count
Example
Input
{1, 2, 3, 4}, 4
Expected output
10
Show a hint
Write down the input contract and the failure cases before coding.
local runtime
RUNTIME OUTPUT
Use your C runtime locally, then compare with solution.c.
Use your local runtime, then review the reference solution
LEARN FROM THE SOLUTION
Why the solution works.
An array parameter is adjusted to a pointer, so the function needs an explicit length. Checking both the pointer and length before the loop makes the empty case safe; the strict index bound prevents an off-by-one read.
What this exercise teaches
Array indexing
Pointer parameters
Precondition checks
A PRACTICAL PLAN
Work through Sum an integer array safely with intent.
Translate the contract.Turn the requirements into a short checklist before editing your-solution.c.
Use the example as evidence.Predict the result for the supplied input, then add one boundary case such as an empty value, a limit, or unexpected input.
Review the implementation.Compare your choices against solution.c only after a real attempt.
EXERCISE FAQ
Before you move on.
What does “Sum an integer array safely” teach?
This beginner C exercise focuses on Array indexing, Pointer parameters, Precondition checks. Its requirements define the exact behavior to implement before you write code.
How should I validate this C solution?
Start with the displayed example input and expected output, then test a boundary case suggested by the requirements. Write and compile the starter in your local C environment, exercise the example and edge cases, then compare your approach with solution.c.
When should I open the reference solution?
Attempt Sum an integer array safely first. Then open the read-only solution file to compare the contract, edge-case handling, and implementation choices—not simply to copy the final code.