Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This code compiles with 'gcc -Wall -Werror -c':</p> <h3>data.h</h3> <pre><code>typedef struct { double ***grid; } Solver; </code></pre> <h3>gs.h</h3> <pre><code>extern void GS_init(double ***grid); </code></pre> <h3>gs.c</h3> <pre><code>#include "data.h" #include "gs.h" #include &lt;stdlib.h&gt; static Solver _solver; void anonymous(void) { _solver.grid = malloc(32 * sizeof(double)); GS_init(_solver.grid); } </code></pre> <hr> <p>Derek asked:</p> <blockquote> <p>Why does this work? Is it because of the extern keyword?</p> </blockquote> <p>The 'extern' is not material to making it work, though I always use it.</p> <blockquote> <p>When I have to flesh out GS_init() in, say compute.c, would I write <code>void GS_init(double ***grid){ //loop over grid[i][j][k] setting to zero }</code></p> </blockquote> <p>Sort of...yes, the GS_init() code could do that if the data structure is set up properly, which is going to need more information than there is currently visible in the structure.</p> <p>For the compiler to process:</p> <pre><code>grid[i][j][k] = 0.0; </code></pre> <p>the code has to know the valid ranges for each of i, j, and k; assume the number of rows in each dimension are N<sub>i</sub>, N<sub>j</sub>, N<sub>k</sub>. The data 'structure' pointed to by <code>grid</code> must be an array of N<sub>i</sub> 'double **' values - which must be allocated. Each of those entries must point to N<sub>j</sub> 'double *' values. So, you have to do more allocation than a single <code>malloc()</code>, and you have to do more initialization than just setting everything to zero.</p> <p>If you want to use a single array of doubles only, you will have to write a different expression to access the data:</p> <pre><code>grid[(i * Ni + j) * Nj + k] = 0.0; </code></pre> <p>And under this scenario, <code>grid</code> would be a simple <code>double *</code> and not a triple pointer.</p>
 

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