Sarah
Sarah

Reputation: 1644

Passing row of static 2-d array to function in C++

This is a really elementary question. Nonetheless, I haven't found a solution after studying dozens of semi-relevant examples online.

I have a two-dimensional array of doubles whose size is known at compile time: double demPMFs[ NUM_DEM_PARAMS ][ NUM_AGE_CATEGORIES ]. Array entries are populated by input files early in the program. I'd like to pass individual rows as one-dimensional arrays to functions later in the program. I'd ideally like to maintain separate names for each row:

#define LSPAN_PMF demPMFs[0][]
#define FLEDGE_PMF demPMFs[1][]
#define PAIR_PMF demPMFs[2][]
#define BIRTH_AGE_PMF demPMFs[3][]
#define SPLIT_AGE_PMF demPMFs[4][]

(Here, NUM_DEM_PARAMS = 5;). Below is a failed attempt to pass a row to a function:

int calcDeath( double demPMFs[][ NUM_AGE_CATEGORIES ] ) {
  int age_death = rmultinom( LSPAN_PMF, NUM_AGE_CATEGORIES );
  return age_death;
} 

int rmultinom( const double p_trans[], int numTrans )
   // ...[code snipped]...
}

I'm getting compiler errors about the prototypes now; I expect to run into problems with the const declaration too. I can go into the details of the errors if people think they're relevant, but I suspect there's a lot to set straight already.

Upvotes: 0

Views: 611

Answers (1)

Georg Fritzsche
Georg Fritzsche

Reputation: 99094

Instead of using array[index][], use array[index]:

#define LSPAN_PMF demPMFs[0]
// ... etc.

But why obfuscate working with arrays so much? Using named indices would be much clearer:

enum {
    IndexLspan,
    IndexFledge,
    // ...
};

int calcDeath( double demPMFs[][ NUM_AGE_CATEGORIES ] ) {
    int age_death = rmultinom( demPMFs[IndexLspan], NUM_AGE_CATEGORIES );

Continuing, why not use the containers from the C++ standard library in the first place?

Upvotes: 2

Related Questions