title: Representing Cell Arrays (from MATLAB) in C
body: <p>Question: How do I design a better interface between Cell arrays and independent Matrix objects?</p>
  
  <p>I am converting a MATLAB code that uses cell arrays and cell arrays of cell arrays to C. I created a Matrix datatype and a Cell data-type. They are illustrated below.</p>
  
  <p>The Matrix datatype</p>
  
  <pre><code>typedef struct{
    double * array; // row major format
    int rows;
    int cols;
  } Matrix;
  </code></pre>
  
  <p>and the Cell datatype</p>
  
  <pre><code>typedef struct{
    Matrix * array; // row major format
    int rows;
    int cols;
  } Cell;
  </code></pre>
  
  <p>Fortunately, the cell array of cell arrays in the code is a simple one dimensional array of cells which I can represent as an array of cell objects.</p>
  
  <p>In the original code, independent matrix objects and elements of a cell array (another matrix) appear together in expressions. For example:</p>
  
  <pre><code>a = rand(10);
  % say, b is a cell array containing other matrices
  % c = some expression involving an element of the cell array b and a
  c = a + b{1,2};
  % assuming dimensions agree
  </code></pre>
  
  <p>Now, in my representation, when I create a cell object, I have allocated rows * cols of Matrix objects and assigned the pointer to the array of Matrix objects to array (inside cell). Assume the Matrix objects are appropriately initialized later in the code (before using them)</p>
  
  <p>The independent matrix objects that I allocate dynamically are accessed by de-referencing pointers pointing to them and the accessor routines for cell arrays return Matrix objects instead of a pointer to a Matrix object.</p>
  
  <pre><code>// Function signature for accessor routine of cell object 
  Matrix get_mat_from_cell(Cell * cell, int row, int col);
  
  // Independent Matrix object - dynamically allocated as size is known
  // at run-time
  Matrix * matrixA = (Matrix *) malloc(sizeof(Matrix));
  
  Matrix matrixB = get_mat_from_cell(someCell, 1, 2);
  
  add(matrixA, &amp;matrixB, matrixC); // adds matrixA, matrixB and stores in a matrixC
  </code></pre>
  
  <p>The thing that tickles me is in the add function (for instance), to get a uniform interface that accepts pointers to matrices for all 3 arguments, I have to pass the address of matrixB. It either looks uniform at the function interface level - like add(Matrix *, Matrix *, Matrix *) or uniform at function call level - add(Matrix *, Matrix, Matrix *) and not both ways. </p>
  
  <p>I could achieve uniformity by declaring the array inside the Cell object as a double pointer but I have to de-reference twice before I can get to a Matrix object and wonder if it will be a performance bottleneck as these cells are really large and are frequently accessed. </p>
  
  <p>How can I design this interface better?</p>
  
  <p>Thank you.   </p>