title: How can I define an arbitrarily-sized 2D array and then determine its dimensions at compile-time?
body: <p><strong>Executive summary:</strong></p>
  
  <ol>
  <li>How can I define an arbitrarily-sized 2D array in C?</li>
  <li>How can I determine the dimensions of that array at compile-time?</li>
  </ol>
  
  <p><strong>Full disclosure:</strong></p>
  
  <p>I'm writing code for an embedded controller. My application requires several lookup tables with different sizes which will all be used by one lookup function (a binary search). Here is what I have so far:</p>
  
  <pre><code>typedef struct
  {
      unsigned char count;        // number of rows in the table
      unsigned char width;        // number of bytes in each row
      const unsigned char * data; // pointer to table data[count][width]
  }
  LookupTable;
  
  // returns the index of a value from within a table
  unsigned char Lookup(unsigned long value, const LookupTable * table);
  </code></pre>
  
  <p>This part is working. What I would like to do now is define these tables in my source without having to manually enter the <code>count</code> and <code>width</code> constants. Here is what I am doing now:</p>
  
  <pre><code>#define T1_count 100
  #define T1_width 3
  const unsigned char table1_data[T1_count][T1_width] = 
  {
      { 0x12, 0x34, 0x56 },
      { 0x12, 0x38, 0x12 },
      ...
  };
  
  const LookupTable table1 = { T1_count, T1_width, table1_data };
  </code></pre>
  
  <p>Here is what I would <em>like</em> to be able to do (pseudo-code, since this array definition will not actually compile):</p>
  
  <pre><code>const unsigned char table1_data[] = 
  {
      { 0x12, 0x34, 0x56 },
      { 0x12, 0x38, 0x12 },
      ...
  };
  
  const LookupTable table1 =
  {
      get_count_expr(table1_data),
      get_width_expr(table1_data),
      table1_data
  };
  </code></pre>
  
  <p>Obviously, <code>get_count_expr</code> and <code>get_width_expr</code> would have to be constant expressions of some sort, based on the size of the table, and not actual function calls.</p>
  
  <p>To be clear, no part of this design is cast in stone. I'm just posting what I have so far, in the hopes that my intent is clear. Any ideas for improvement would be appreciated.</p>
  
  <p><strong>The "why":</strong></p>
  
  <p>These tables will be changed often, and it would make maintenance easier if entries could be added and removed, or the width of a table changed without having to manually adjust the constants each time. Having to keep track of the sizes manually can be error-prone and violates <a href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself" rel="nofollow">DRY</a>. I'm looking for a better way.</p>