Simvik

Compare two structs

Test two structs for equality without being fooled by padding. A medium embedded C problem (Structs, unions and memory layout), run and graded in the browser.

medium · Structs, unions and memory layout · padding · comparison

Return true if the two readings have the same id and the same value.

The starter compares the raw bytes. It passes the visible tests and is still wrong. Find out why and fix it.

Starter code

bool reading_equal(const reading_t *a, const reading_t *b) {
  return memcmp(a, b, sizeof *a) == 0;
}

Example tests

Equal readings

reading_t a = { 1, 500 }, b = { 1, 500 };
printf("%d\n", reading_equal(&a, &b));

Expected output:

1

Different values

reading_t a = { 1, 500 }, b = { 1, 501 };
printf("%d\n", reading_equal(&a, &b));

Expected output:

0

Learn it first

More Structs, unions and memory layout problems