简体   繁体   中英

C structs, pointers to structs, and proper initialization

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:

typedef struct neuron {
    double *inputweights;
    double *neuronweights;
    double value;
} NEURON; 

typedef struct network {
    NEURON **neurons;
    double *outputs;
} NETWORK;

Initially, I tried to initialize these like this:

NEURON* myvariable;

But of course that didn't work because no memory was actually assigned. I know that I can initialize it like this:

NEURON myvariable;
NEURON* ptr = &myvariable;

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:

NETWORK mynetwork;
for (i = 0; i < NEURON_COUNT; i++) {
    NEURON myneuron;
    reset_neuron(&myneuron); // Basically a zero fill of the arrays
    mynetwork->neurons[i]=&myneuron;
    myneuron->inputweights[0] = 1; // Sets the current neuron, first input
    printf("First neuron, first input is %f\n", mynetwork->neurons[0]->inputweights[0]);
    // The printf gives 1 on the first iteration, and 0 on every following iteration.
}

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:

NEURON* myvariable = malloc(sizeof(NEURON));

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?

That's exactly what malloc is for. When you need a varying number of objects of a particular type and need to control where they are allocated, you use malloc . Why does it seem like a kludge?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM