【发布时间】:2020-01-05 20:49:58
【问题描述】:
我有一个名为 create() 的函数,它返回一个指向名为 ann 的结构的指针,如下所示
typedef struct ann {
int inputs; /* Number of input neurones */
int hidden_layers; /* Number of hidden layers */
int hidden; /* Number of hidden neurones */
int outputs; /* Number of output neurons. */
int weights; /* Total nof weigths(chromosomes)*/
int neurons; /* Total Number of neurones */
double *weight; /* The weights(genotype) */
double *output; /* Output */
double fitness; /* Total fitness of the network */
double *delta;
actfun activation_hidden; /* Hidden layer activation func */
actfun activation_output; /* Output layer activation func */
} ann;
函数create()的原型
ann *create(int inputs, int hidden_layers, int hidden, int outputs);
我需要一个 ann 数组,所以我有以下内容
int population_size = 10;
ann *population = malloc ( population_size * sizeof(ann));
for( i = 0; i < population_size; i++ ){
population[i] = create( trainset->num_inputs, 1 , hidden, trainset->num_outputs);
}
但我收到以下错误
error: incompatible types when assigning to type ‘ann {aka struct ann}’ from type ‘ann * {aka struct ann *}’
我的问题是如何在 population 中对当前元素进行类型转换,以便返回的结构(指针) ann 可以存储在 population 中
这里要求的是函数create()的完整代码
ann *create ( int inputs, int hidden_layers, int hidden, int outputs ) {
if (hidden_layers < 0) return 0;
if (inputs < 1) return 0;
if (outputs < 1) return 0;
if (hidden_layers > 0 && hidden < 1) return 0;
const int hidden_weights = hidden_layers ? (inputs+1) * hidden + (hidden_layers-1) * (hidden+1) * hidden : 0;
const int output_weights = (hidden_layers ? (hidden+1) : (inputs+1)) * outputs;
const int total_weights = (hidden_weights + output_weights);
const int total_neurons = (inputs + hidden * hidden_layers + outputs);
/* Allocate extra size for weights, outputs, and deltas. */
const int size = sizeof(ann) + sizeof(double) * (total_weights + total_neurons + (total_neurons - inputs));
ann *ret = malloc(size);
if (!ret) return 0;
ret->inputs = inputs;
ret->hidden_layers = hidden_layers;
ret->hidden = hidden;
ret->outputs = outputs;
ret->weights = total_weights;
ret->neurons = total_neurons;
/* Set pointers. */
ret->weight = (double*)((char*)ret + sizeof(ann));
ret->output = ret->weight + ret->weights;
ret->delta = ret->output + ret->neurons;
ann_randomize(ret);
ret->activation_hidden = ann_act_sigmoid_cached;
ret->activation_output = ann_act_sigmoid_cached;
ann_init_sigmoid_lookup(ret);
return ret;
}
【问题讨论】:
-
不返回指针,返回结构体。
-
要么这样,要么将其设为指针数组而不是结构数组。
-
@Barmar 怎么做,请帮助我是 c 新手
-
我支持@Barmar。但是使用指针数组,您将不得不在 create() 中移动动态分配(恕我直言,这更正确)。