You are not logged in.

#1 2009-06-08 20:13:47

ogronom
Member
From: Toronto, Canada
Registered: 2008-05-06
Posts: 123

[SOLVED] C: allocate memory for structures (noob)

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

#2 2009-06-08 20:42:22

Cerebral
Forum Fellow
From: Waterloo, ON, CA
Registered: 2005-04-08
Posts: 3,108
Website

Re: [SOLVED] C: allocate memory for structures (noob)

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

#3 2009-06-08 20:50:52

ogronom
Member
From: Toronto, Canada
Registered: 2008-05-06
Posts: 123

Re: [SOLVED] C: allocate memory for structures (noob)

Thanks

Offline

Board footer

Powered by FluxBB