用伪代码,我想替换为:
ra = (double *) realloc(ra, Num*sizeof(*ra));
dec = (double *) realloc(dec, Num*sizeof(*dec));
zobs = (double *) realloc(zobs, Num*sizeof(*zobs));
M_B = (double *) realloc(M_B, Num*sizeof(*M_B));
与
例如mem_allocate(&ra,&dec,&zobs,&M_B)
哪里
mem_allocate(arg1, arg2,..., arg4){
for argi in arg1 to arg4{
argi = (double *) realloc(argi, Num*sizeof(*argi))
}
}
最佳答案
为了完整起见,我举了一个例子
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
bool mem_allocate (double *vars[], size_t N_vars, size_t newWidth)
{
double *temp;
printf("\n");
for (size_t i=0; i<N_vars; i++)
{
temp = realloc(vars[i], newWidth*sizeof(*temp));
if (temp != NULL)
{
printf ("temp: %p\n", (void *)temp);
vars[i] = temp;
}
else
{
return false;
}
}
printf("\n");
return true;
}
int main (void)
{
double *var1 = malloc(sizeof(*var1));
double *var2 = malloc(sizeof(*var2));
double *var3 = malloc(sizeof(*var3));
double *var4 = malloc(sizeof(*var4));
printf ("var1: %p\n", (void *)var1);
printf ("var2: %p\n", (void *)var2);
printf ("var3: %p\n", (void *)var3);
printf ("var4: %p\n", (void *)var4);
double *vars[4];
vars[0] = var1;
vars[1] = var2;
vars[2] = var3;
vars[3] = var4;
if (mem_allocate (vars, sizeof(vars)/sizeof(vars[0]), 200) == true)
{
var1 = vars[0];
var2 = vars[1];
var3 = vars[2];
var4 = vars[3];
printf ("var1: %p\n", (void *)var1);
printf ("var2: %p\n", (void *)var2);
printf ("var3: %p\n", (void *)var3);
printf ("var4: %p\n", (void *)var4);
}
return 0;
}
在函数mem_allocate中更改
varx
意味着3星实现,我真的不喜欢。显然,必须检查所有
malloc
返回值。关于c - C语言中简洁的动态内存分配,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42116162/