gpt4 book ai didi

c - C 中的简洁动态内存分配

转载 作者:行者123 更新时间:2023-11-30 19:09:59 25 4
gpt4 key购买 nike

在伪代码中,我想替换:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com