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

3
  • possible duplicate of C pointer to two dimensional array Commented Apr 9, 2014 at 23:14
  • I am assuming you do not want an independent copy? Commented Apr 9, 2014 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. Commented Apr 9, 2014 at 23:46

3 Answers 3

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

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.
@MattMcNabb, Thanks for the edit and the comment. I was using Vim's autocomplete and did not pay enough attention. :)
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;

1 Comment

That reference should be assigned to something, right ? Given the OP's question an only-slightly-wicked stack of ternary expressions would work.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.