Difficulty creating a contiguous 2D array on the heap
<p>I am currently implementing an N x 2 matrix of <code>floats</code> on the heap as follows:</p>

<pre><code>float **matrix = malloc(sizeof(float*) * n_cols);

for (int i = 0; i &lt; n_cols; ++i) {
    matrix[i] = malloc(sizeof(float) * 2);
}
</code></pre>

<p>The elements of <code>matrix</code> are not contiguous in memory, making this data structure cache unfriendly (as I understand it). I am trying to re-write the above to create a genuine 2D array on the heap. Based on some previous SO posts, I tried the following:</p>

<pre><code>float (*matrix)[2] = malloc(sizeof(float) * n_cols * 2);
</code></pre>

<p>However, this lead to a segmentation fault when I ran my code.</p>