如果我有你的代码并且必须改进它,我会选择
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
// The kernel style guide https://www.kernel.org/doc/html/v4.10/process/coding-style.html discourages typedefs for structs
typedef struct moeda {
double *return_value;
} moeda;
// return a struct here:
moeda initialize_return(int a)
{
moeda ret;
ret.return_value = malloc(a*sizeof(double));
return ret;
}
int main(void) {
long int a=250;
moeda m = initialize_return(a);
m.return_value[0] = 2000;
printf("%lf", m.return_value[0]);
return 0;
}
(最好所有标识符都用英文)。
这将是第一步。然后我可能会意识到这个结构并不是真的需要并替换它:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
double * initialize_double_array(int a)
{
return malloc(a*sizeof(double));
}
int main(void) {
long int a=250;
double * arr = initialize_double_array(a);
arr[0] = 2000;
printf("%lf", arr[0]);
return 0;
}
OTOH,如果上述结构中还有其他字段,我可能会决定它们是否应该与这个数组一起初始化。
一些变种:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
// The kernel style guide https://www.kernel.org/doc/html/v4.10/process/coding-style.html discourages typedefs for structs
struct moeda {
int num_values;
double *values;
};
// only fill a struct here:
// i. e. take a pre-initialized struct and work with it:
void moeda_alloc_values(struct moeda * data)
{
data->return_value = malloc(data->num_values * sizeof(double));
}
// return a struct here:
struct moeda initialize_moeda(int num)
{
struct moeda ret;
ret.num_values = num;
ret.return_value = malloc(num * sizeof(double));
// or just moeda_alloc_values(&ret);
return ret;
}
int main(void) {
long int a=250;
struct moeda m = initialize_return(a);
m.return_value[0] = 2000;
printf("%lf", m.return_value[0]);
struct moeda m2;
m2.num_values = 20;
moeda_alloc_values(&m2);
m2.return_value[0] = 2000;
printf("%lf", m2.return_value[0]);
return 0;
}
结构返回函数的优点是在返回后你有一个“容易填充”的结构。
另一个通过指针修改结构的函数的优点是它可以处理任何可能预填充、可能分配的结构,并且它可以处理单个字段,而不必考虑所有字段。