Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>With your allocation pattern, you can't do a simple copy because of the multiple allocations in the second loop. It depends on what you're really after. You can arrange things so that you do just one allocation of a set of pointers — by setting up pointers into your current 1D array so that you can access it as a 2D array. Alternatively, you can create a copy of your 1D array and then set up the pointers (2 allocations, 1 copy, 1 initialization loop). Since the only issue is whether to copy the original allocation, the main answer will work on the original data.</p> <p>You have:</p> <pre><code>int N, A, B; A = ...; B = ...; N = A * B; double *a_1d = malloc(N * sizeof(double)); ...check and load a_1d... </code></pre> <p>Now you can create a 2D 'array' by:</p> <pre><code>double **a_2d = malloc(A * sizeof(double *)); ...check that allocation succeeded... for (int i = 0; i &lt; A; i++) a_2d[i] = &amp;a_1d[i * B]; </code></pre> <p>With this initialization done, you can now use:</p> <pre><code>for (int i = 0; i &lt; A; i++) for (int j = 0; j &lt; B; j++) a_2d[i][j] = ...; </code></pre> <p>If you really need to duplicate the original <code>a_1d</code> array, you'd add:</p> <pre><code>double *a_1d_copy = malloc(N * sizeof(double)); ...check that the allocation succeeded... memmove(a_1d_copy, a_1d, N * sizeof(double)); </code></pre> <p>and then you can reference <code>a_1d_copy</code> instead of <code>a_1d</code> in setting up <code>a_2d</code>.</p> <p>Remember that when it comes time to free things, you need to release both <code>a_1d</code> and <code>a_2d</code> (and <code>a_2d_copy</code> if you're using that).</p>
    singulars
    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.
    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