Simvik

Return a struct by value

Compute the midpoint of two points and return it as a struct. An easy embedded C problem (Structs, unions and memory layout), run and graded in the browser.

easy · Structs, unions and memory layout · structs · by-value

Return the point halfway between a and b. Each coordinate is the average of the two inputs, with the division truncating toward zero.

Starter code

point_t midpoint(point_t a, point_t b) {
  // Return a new point; a and b are copies and cannot be changed.
  point_t m = { 0, 0 };
  return m;
}

Example tests

Origin to a point

point_t m = midpoint((point_t){ 0, 0 }, (point_t){ 10, 20 });
printf("%d %d\n", m.x, m.y);

Expected output:

5 10

Negative coordinates

point_t m = midpoint((point_t){ -10, -10 }, (point_t){ 10, 20 });
printf("%d %d\n", m.x, m.y);

Expected output:

0 5

Learn it first

More Structs, unions and memory layout problems