/* =============================================================================
 * 06_arrays.c  --  how C arrays are laid out in memory, checked by C itself
 * =============================================================================
 *
 * [Questions this demo answers]
 *   - `T A[L]` is L * sizeof(T) contiguous bytes. Where exactly is A[i]?
 *   - What are the type and value of val[4], val, val+1, &val[2], *(val+3)?
 *   - A nested array int pgh[4][5] and a multi-level array int *univ[3] are
 *     both written x[i][j] in C. How do their layouts differ?
 *   - Why is sizeof(an array) different from sizeof(a pointer)?
 *
 * [How to build & run]
 *   make && ./build/06_arrays
 *
 * [How to read the output]
 *   Addresses are printed as offsets from the start of each array ("x + 8"),
 *   because the absolute addresses change from run to run. Every formula is
 *   checked with assert-like comparisons; the demo prints how many cases
 *   agreed.
 *
 * [Systems link / CS:APP 3.8]
 *   The machine has no arrays, only addresses. Everything here is the rule
 *       &A[i] = A + i * sizeof(T)
 *   applied once (1-D), twice in one address calculation (nested arrays) or
 *   with a memory read in between (multi-level arrays).
 * -------------------------------------------------------------------------- */

#include <stddef.h>
#include <stdint.h>
#include <stdio.h>

#define ZLEN 5
#define PCOUNT 4
typedef int zip_dig[ZLEN];

zip_dig cmu = {1, 5, 2, 1, 3};
zip_dig mit = {0, 2, 1, 3, 9};
zip_dig ucb = {9, 4, 7, 2, 0};
zip_dig pgh[PCOUNT] = {{1, 5, 2, 0, 6}, {1, 5, 2, 1, 3}, {1, 5, 2, 1, 7}, {1, 5, 2, 2, 1}};
int *univ[3] = {mit, cmu, ucb};

/* [Idea] Byte distance from base to p, for printing "x + offset". */
static long off(const void *p, const void *base)
{
    return (long)((const char *)p - (const char *)base);
}

static void part_a(void)
{
    char string[12];
    int val[5];
    double a[3];
    char *p[3];
    printf("PART A: array allocation -- element i is at x + i*sizeof(T)\n");
    printf("  %-16s %-6s %s\n", "declaration", "bytes", "element offsets from x");
    printf("  %-16s %-6zu", "char string[12]", sizeof string);
    for (int i = 0; i < 12; i++) printf(" %ld", off(&string[i], string));
    printf("\n  %-16s %-6zu", "int val[5]", sizeof val);
    for (int i = 0; i < 5; i++) printf(" %ld", off(&val[i], val));
    printf("\n  %-16s %-6zu", "double a[3]", sizeof a);
    for (int i = 0; i < 3; i++) printf(" %ld", off(&a[i], a));
    printf("\n  %-16s %-6zu", "char *p[3]", sizeof p);
    for (int i = 0; i < 3; i++) printf(" %ld", off(&p[i], p));
    printf("\n  (the array ends at x + 12, 20, 24, 24: one past the last element)\n\n");
}

static void part_b(void)
{
    int val[5] = {1, 5, 2, 1, 3};
    int i = 3;
    printf("PART B: the slides' access table for int val[5] = {1, 5, 2, 1, 3}\n");
    printf("  %-10s %-6s %s\n", "expression", "type", "value");
    printf("  %-10s %-6s %d\n", "val[4]", "int", val[4]);
    printf("  %-10s %-6s %s\n", "val[5]", "int", "?? -- one past the end: reading it is undefined"
                                                  " (not evaluated here)");
    printf("  %-10s %-6s %d   (same as val[3])\n", "*(val+3)", "int", *(val + 3));
    printf("  %-10s %-6s x + %ld\n", "val", "int *", off(val, val));
    printf("  %-10s %-6s x + %ld\n", "val+1", "int *", off(val + 1, val));
    printf("  %-10s %-6s x + %ld   (same as val+2)\n", "&val[2]", "int *", off(&val[2], val));
    printf("  %-10s %-6s x + %ld  (= 4*i with i = %d; same as &val[i])\n\n",
           "val+i", "int *", off(val + i, val), i);
}

static void part_c(void)
{
    /* The slides' "Example: Array Access" (additional slides). */
    zip_dig loc[PCOUNT] = {{1, 5, 2, 0, 6}, {1, 5, 2, 1, 3}, {1, 5, 2, 1, 7}, {1, 5, 2, 2, 1}};
    int *linear_zip = (int *)loc;
    int *zip2 = (int *)loc[2];
    int result = loc[0][0] + linear_zip[7] + *(linear_zip + 8) + zip2[1];
    printf("PART C: the slides' quiz -- one 2-D array seen as one long 1-D array\n");
    printf("  pgh[0][0] + linear_zip[7] + *(linear_zip + 8) + zip2[1]\n");
    printf("  = %d + %d + %d + %d = %d   (linear_zip[7] is row 1, column 2;\n"
           "    zip2 = pgh[2], so zip2[1] is pgh[2][1])\n\n",
           loc[0][0], linear_zip[7], *(linear_zip + 8), zip2[1], result);
}

static void part_d(void)
{
    int agree = 0, cases = 0;
    printf("PART D: nested array int pgh[4][5] -- ONE block of 4*5*4 = %zu bytes\n", sizeof pgh);
    for (int r = 0; r < PCOUNT; r++) {
        printf("  pgh[%d] starts at pgh + %-3ld:", r, off(pgh[r], pgh));
        for (int c = 0; c < ZLEN; c++) {
            printf(" %d", pgh[r][c]);
            cases++;
            agree += off(&pgh[r][c], pgh) == 4L * (ZLEN * r + c);
        }
        printf("\n");
    }
    printf("  &pgh[i][j] == pgh + 4*(5*i + j): %d of %d elements agree\n\n", agree, cases);

    agree = cases = 0;
    printf("PART E: multi-level array int *univ[3] = {mit, cmu, ucb} -- 3 POINTERS\n");
    printf("  sizeof univ = %zu (3 pointers of 8 bytes); the rows live elsewhere:\n", sizeof univ);
    const char *names[3] = {"mit", "cmu", "ucb"};
    for (int r = 0; r < 3; r++) {
        printf("  univ[%d] at univ + %ld holds %-4s  (row %+ld bytes from cmu):", r,
               off(&univ[r], univ), names[r], off(univ[r], cmu));
        for (int c = 0; c < ZLEN; c++) {
            printf(" %d", univ[r][c]);
            cases++;
            int *row = *(int **)((char *)univ + 8 * r);          /* memory read #1 */
            agree += univ[r][c] == *(int *)((char *)row + 4 * c); /* memory read #2 */
        }
        printf("\n");
    }
    printf("  univ[i][j] == Mem[Mem[univ + 8*i] + 4*j]: %d of %d elements agree\n", agree, cases);
    printf("  (where the rows sit is up to the compiler and linker; C promises no order,\n"
           "   and a row could be anywhere -- two pointers could even share one row)\n\n");
}

static void part_f(void)
{
    int A1[3];
    int *A2;
    int A3[3][5];
    int *A4[3];
    int (*A5)[3];
    (void)A1; (void)A2; (void)A3; (void)A4; (void)A5;
    printf("PART F: arrays vs pointers -- what sizeof sees\n");
    printf("  %-14s %-10s %-10s %s\n", "declaration", "sizeof An", "sizeof *An", "sizeof **An");
    printf("  %-14s %-10zu %-10zu %s\n", "int A1[3]", sizeof A1, sizeof *A1, "-");
    printf("  %-14s %-10zu %-10zu %s\n", "int *A2", sizeof A2, sizeof *A2, "-");
    printf("  %-14s %-10zu %-10zu %zu\n", "int A3[3][5]", sizeof A3, sizeof *A3, sizeof **A3);
    printf("  %-14s %-10zu %-10zu %zu\n", "int *A4[3]", sizeof A4, sizeof *A4, sizeof **A4);
    printf("  %-14s %-10zu %-10zu %zu\n", "int (*A5)[3]", sizeof A5, sizeof *A5, sizeof **A5);
    printf("  An ARRAY variable is the storage itself (12, 60, 24 bytes); a POINTER\n"
           "  variable is 8 bytes that may or may not point at storage. A2, A5: no\n"
           "  storage for ints was allocated at all -- *A2 would be a bad reference.\n\n");
}

int main(void)
{
    printf("=== Demo 06: array layout ===\n\n");
    part_a();
    part_b();
    part_c();
    part_d();
    part_f();
    printf("Observations:\n");
    printf("  * T A[L] is L*sizeof(T) contiguous bytes, and A used as a value is a\n"
           "    pointer to A[0]; A+i (pointer arithmetic) means A + i*sizeof(T) bytes.\n");
    printf("  * A nested array is ONE block in row-major order: A[i][j] is at\n"
           "    A + (i*C + j)*sizeof(T) -- one address calculation, one memory read.\n");
    printf("  * A multi-level array is an array of POINTERS: A[i][j] needs a read of\n"
           "    the row pointer first -- two memory reads, but rows can have any length.\n");
    printf("  * C never checks bounds: val[5] compiles and reads whatever comes next.\n");
    return 0;
}
