我正在尝试使用来自 main 的值 malloc 一个结构。我一直在寻找这样做的方法,但找不到答案。我有 3 种类型的硬币,我想将其价格放入ret。如何从结构中声明ret?
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
typedef struct
{
double *ret;
}coin;
void ini(int a)
{
ret = (double*)malloc(a*sizeof(double));
}
int main(void){
long int a=250;
int n_coins=3;
coin *m = (coin*)malloc(n_coins*sizeof(coin));
ini(a);
m[0].ret[0] = 2000;
printf("%lf", m[0].ret[0]);
return 0;
}
最佳答案
如果我有你的代码并且必须改进它,我会去
#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;
}
struct 返回函数的优点是您在返回后拥有一个“易于填充”的结构。
另一个通过指针修改结构的函数的优点是它可以处理任何可能预填充的、可能分配的结构,并且它可以处理单个字段而不必考虑所有字段。
关于结构中数组的 C Malloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49516685/