[英]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. 我正在努力将神经网络模拟器从Perl转换为C。可以运行,但是我对部分代码不满意。 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.
我定义了一个结构网络(类型定义为NETWORK),该结构网络包含一个指向双精度数组的指针和一个指向NEURON的指针数组的指针,这是另一个结构。 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. 这给我的印象是,即使我仍然保持指向最后一个的指针,myneuron始终是/ same /内存位置,所以我一直在重置相同的位置。 Of course I can also use malloc to force each neuron to be different:
当然,我也可以使用malloc强制每个神经元都不同:
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?
有没有一种方法可以初始化结构指针而不求助于低级的malloc和sizeof?
That's exactly what malloc
is for. 这正是
malloc
目的。 When you need a varying number of objects of a particular type and need to control where they are allocated, you use malloc
. 当您需要不同数量的特定类型的对象并需要控制它们的分配位置时,可以使用
malloc
。 Why does it seem like a kludge? 为什么看起来像个混蛋?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.