1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>

void
initMatrix(size_t m, size_t n,
     double *A,
     ptrdiff_t incRow, ptrdiff_t incCol)
{
    for (size_t i=0; i<m; ++i) {
        for (size_t j=0; j<n; ++j) {
            A[i*incRow+j*incCol] = i*n+j+1;
        }
    }
}

void
printMatrix(size_t m, size_t n,
            const double *A,
            ptrdiff_t incRow, ptrdiff_t incCol)
{
    for (size_t i=0; i<m; ++i) {
        for (size_t j=0; j<n; ++j) {
            printf("%10.3lf", A[i*incRow+j*incCol]);
        }
        printf("\n");
    }
    printf("\n");
}

//We no longer use the data segment

//#define MAX_ROWS    100
//#define MAX_COLS    100
//
//double A[MAX_ROWS*MAX_COLS];

int main()
{
    size_t m = 5;
    size_t n = 8;

    size_t incRow = n;
    size_t incCol = 1;

    // Instead allocate the memory on the heap
    double *A = (double *) malloc(m*n*sizeof(double));


    initMatrix(m, n, A, incRow, incCol);
    printMatrix(m, n, A, incRow, incCol);

    // make additions here:

    // 1) initialize column wise
    initMatrix(n, m, A, incCol, incRow);
    printMatrix(m, n, A, incRow, incCol);

    // 2) print second row
    printMatrix(1, n, &A[1*incRow], incRow, incCol);

    // 3) print third col
    printMatrix(m, 1, &A[2*incCol], incRow, incCol);

    // 4) init the sub-matrix B that refers to A(2:4, 3:6)
    initMatrix(3, 4, &A[2*incRow+3*incCol], incRow, incCol);

    // 5) print matrix A again
    printMatrix(m, n, A, incRow, incCol);

    // Release memory
    free(A);

    return 0;
}