You are not logged in.
Hi guys, quite noob question about structures in C and allocation memory for it
I have (say) structure
typedef struct
{
int limit, size;
double x, power, bound;
double * c;
}
PowerSeries
and functions that alocates memory for it
PowerSeries * power_series_alloc(int n)
{
PowerSeries * tmp;
tmp = (PowerSeries *) malloc(sizeof(PowerSeries));
assert(tmp);
tmp->c = (double *) malloc(n*sizeof(double));
assert(tmp->c);
tmp->limit=n;
tmp->size=0;
tmp->power=0.;
tmp->x=0.;
return tmp;
}
And I have another structure
typedef struct
{
PowerSeries uppercomponent;
PowerSeries lowercomponent;
}
DoublePowerSeries;
How to write properly
DoublePowerSeries *
double_power_series_alloc(int n);
that basically calls twice power_series_alloc for uppercomponent, and lower component.
Last edited by ogronom (2009-06-08 20:51:21)
Offline
You'd want to break out your initialization from your allocation.
Probably like this:
void power_series_init(PowerSeries* tmp, int n)
{
tmp->c = (double *) malloc(n*sizeof(double));
assert(tmp->c);
tmp->limit=n;
tmp->size=0;
tmp->power=0.;
tmp->x=0.;
}
PowerSeries * power_series_alloc(int n)
{
PowerSeries * tmp;
tmp = (PowerSeries *) malloc(sizeof(PowerSeries));
assert(tmp);
power_series_init(tmp, n);
return tmp;
}
DoublePowerSeries * double_power_series_alloc(int in)
{
DoublePowerSeries* tmp = malloc(sizeof(DoublePowerSeries));
assert(tmp);
power_series_init(&tmp->uppercomponent, n);
power_series_init(&tmp->lowercomponent, n);
return tmp;
}
Offline
Thanks
Offline