Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>For clarification, suppose you declare:</p> <pre><code>int my_static_array[row][col]; </code></pre> <p>What is the type of my_static_array vs the malloc'd array (let's call it my_malloc array) in pmg's answer? my_static_array is a contiguous row*col*sizeof(int) number of bytes in memory, with an int* pointer to its beginning. When computing my_static_array[x][y], the compiler knows to do (because they are stored in <a href="http://en.wikipedia.org/wiki/Row-major_order" rel="nofollow">row-major order</a>):</p> <pre><code>*(addr(my_static_array) + [sizeof(int)*col*x] + [sizeof(int)*y]) </code></pre> <p>This is why I need to pass in the col value for C:</p> <pre><code>(1) func(int my_static_array[][col]) (2) func(int my_static_array[][]) </code></pre> <p>In (1), the compiler knows how to compute the address properly for the static array. In (2), the compiler does not have enough information. This is why (1) compiles, and (2) will not.</p> <p>If it is the malloc'd array, however, one can pass:</p> <pre><code>func(int** my_malloc_array) </code></pre> <p>Since it is a pointer to a contiguous array of 1D arrays, the compiler needs no help. my_malloc_array[x][y] is done simply:</p> <pre><code>*(*(addr(my_malloc_array)+x)+y) </code></pre> <p>The compiler needs no other information about its dimensionality in order to compute.</p> <p>So, what is the lesson? 2D arrays are <strong>NOT</strong> the same as an array of pointers to 1D arrays. The former has type int (*my_static_array)[row*col] -- pointer to an array of <strong>row*col</strong> elements, the latter has type int** -- pointer to an array of <strong>row</strong> pointers.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload