Question 6 of 148 points

Question 6 · 8 points

Trace function pointers through a union

Assuming the union members share the expected contiguous layout, state exactly what is printed and show how each pointer expression selects its function.

int shift1(int v) { return v << 1; }
int shift2(int v) { return v << 2; }
int shift3(int v) { return v << 3; }
int shift4(int v) { return v << 4; }

typedef int (*Transform)(int);

union MemoryLayout {
    Transform linear[4];
    Transform table[2][2];
};

int main(void) {
    union MemoryLayout mem = {
        .linear = {shift1, shift2, shift3, shift4}
    };

    Transform (*pTable)[2] = mem.table;
    Transform (*pLinear)[4] = &mem.linear;

    int x = (*(pTable + 1))[0](3);

    Transform *pFlat = (Transform *)(pLinear + 1);
    int y = (*(pFlat - 3))(3);

    printf("%d %d\n", x, y);
    return 0;
}

Your response

Your answer

0 words