Note that there are some explanatory texts on larger screens.

plurals
  1. POC structs, pointers to structs, and proper initialization
    text
    copied!<p>I'm working on converting a neural network simulator from Perl to C. I have it working, but I'm not happy with part of my code. I've defined a struct network (typedefed to NETWORK) which contains a pointer to an array of doubles and a pointer to an array of pointers to NEURONs, which is another struct. Here is how they are defined:</p> <pre><code>typedef struct neuron { double *inputweights; double *neuronweights; double value; } NEURON; typedef struct network { NEURON **neurons; double *outputs; } NETWORK; </code></pre> <p>Initially, I tried to initialize these like this:</p> <pre><code>NEURON* myvariable; </code></pre> <p>But of course that didn't work because no memory was actually assigned. I know that I can initialize it like this:</p> <pre><code>NEURON myvariable; NEURON* ptr = &amp;myvariable; </code></pre> <p>But when I tried to do that into a loop, and stored the pointers in an array, it seemed like the previous pointers were lost or reset each iteration, and I was getting all sorts of errors. I was doing something like this:</p> <pre><code>NETWORK mynetwork; for (i = 0; i &lt; NEURON_COUNT; i++) { NEURON myneuron; reset_neuron(&amp;myneuron); // Basically a zero fill of the arrays mynetwork-&gt;neurons[i]=&amp;myneuron; myneuron-&gt;inputweights[0] = 1; // Sets the current neuron, first input printf("First neuron, first input is %f\n", mynetwork-&gt;neurons[0]-&gt;inputweights[0]); // The printf gives 1 on the first iteration, and 0 on every following iteration. } </code></pre> <p>This gives me the impression that myneuron is always the /same/ memory location, even though I'm still keeping a pointer to the last one, so I keep resetting the same place. Of course I can also use malloc to force each neuron to be different:</p> <pre><code>NEURON* myvariable = malloc(sizeof(NEURON)); </code></pre> <p>And that works, but that seems a bit like a kludge. Should I be bothering to use pointers to my structs at all? Is there a way to initialize a struct pointer without resorting to the low-level malloc and sizeof? </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