0

I have some 2D arrays of a static size:

double quickStats[NUM_REPETITIONS][NUM_TRIALS];
double mergeStats[NUM_REPETITIONS][NUM_TRIALS];
double bstStats[NUM_REPETITIONS][NUM_TRIALS];

Later, I want a reference to one of them:

double stats[NUM_REPETITIONS][NUM_TRIALS];

    if(i == 0) {
        stats = quickStats;
    }
    else if(i == 1) {
        stats = mergeStats;
    }
    else if(i == 2) {
        stats = bstStats;
    }

However, this does not work.

What can I do to do what I am trying to do without nested for loops to manually copy each element into the reference array?

I just need to read from stats, it is to avoid redundant code.

Thanks

jmasterx
  • 52,639
  • 96
  • 311
  • 557
  • possible duplicate of [C pointer to two dimensional array](http://stackoverflow.com/questions/14808908/c-pointer-to-two-dimensional-array) – Cloud Apr 09 '14 at 23:14
  • I am assuming you do not want an independent copy? – merlin2011 Apr 09 '14 at 23:19
  • I am assuming you want a pointer not reference? References have to be initialized upon declaration so you cannot assign it later on. Your best bet is using a pointer or declare the reference inside the if branches. – SwiftMango Apr 09 '14 at 23:46

3 Answers3

2

Try this:

#define NUM_REPETITIONS 10
#define NUM_TRIALS 10
double quickStats[NUM_REPETITIONS][NUM_TRIALS];
double mergeStats[NUM_REPETITIONS][NUM_TRIALS];
double bstStats[NUM_REPETITIONS][NUM_TRIALS];

int main(){
    double (* ptr)[NUM_TRIALS] =quickStats;
}
M.M
  • 138,810
  • 21
  • 208
  • 365
merlin2011
  • 71,677
  • 44
  • 195
  • 329
  • Explaining a bit more for OP; with this syntax you would then access elements via `ptr[3][4]`. You can also point to lists of different numbers of repetitions, although the number of trials must remain fixed. – M.M Apr 09 '14 at 23:24
  • @MattMcNabb, Thanks for the edit and the comment. I was using Vim's autocomplete and did not pay enough attention. :) – merlin2011 Apr 09 '14 at 23:45
0

Create a pointer to it like this:

double (*stats)[NUM_REPETITIONS][NUM_TRIALS];

Since your dimensions are known at compile time you can use std::array<> which is more versatile and readable:

std::array<std::array<double, NUM_TRIALS>, NUM_REPETITIONS> stat;
David G
  • 94,763
  • 41
  • 167
  • 253
  • That reference should be assigned to *something*, right ? Given the OP's question an only-slightly-wicked stack of ternary expressions would work. – WhozCraig Apr 09 '14 at 23:24
0

References have to be initialized upon declaration so you cannot assign it later on. Your best bet is using a pointer or declare the reference inside the if branches.

constexpr unsigned int N = 100;

double a[N][N] = {0};

/* Pointer. In your case, N should be NUM_TRAILS here */
double (*a_ptr)[N] = a;


/* Specified Reference Type */
double (&a_ref)[N][N] = a;

/* C++11 Auto Reference */
auto &a_autoref = a;

Test here: Coliru

SwiftMango
  • 15,092
  • 13
  • 71
  • 136