0

if you look at this class, how do I achieve the following:

class foo {

public:

  void foo(double (&arr)[3][4]) { //Constructor
    arr2 = arr; //??? How to assign multidimensional arrays?
  }

  void bar() { //Usage
    double doSomething = arr2[1][0];
  }

private:
  double* arr2[3][4]; //??? How to store this?
}

Thanks everyone!

More explanation: This should be a class, that get a reference to a two-dimensional array in its constructor (foo()). It stores this reference in a member variable, so that some other function (bar()) can access them later.

So what "format" has the member variable and how do I assign the parameter of the constructor to it?

Edit2: As I impement an interface, I can't change signatures to use std::vector>...

powerbar
  • 323
  • 3
  • 14
  • Please explain what you are trying to do and what problems you are having in more detail. – YXD Mar 15 '12 at 14:56
  • This might help: http://stackoverflow.com/questions/2828648/how-to-pass-a-multidimensional-array-to-a-function-in-c-and-c – chris Mar 15 '12 at 14:57
  • 2
    Welcome to Stack Overflow! Unfortunately, this is not a good example of how to ask questions here (hence the -1 vote). You need to do a better job of explaining both what you want and what you've tried so far. See [this guide](http://stackoverflow.com/questions/how-to-ask) for more info. – Michael Kristofik Mar 15 '12 at 15:00
  • @Kristo: Hello ;) I just gave you some more information. – powerbar Mar 15 '12 at 15:03
  • I just added a bunch of new information, so please consider answering it now ;) – powerbar Mar 15 '12 at 15:12
  • Do you really want to just hold a "reference" in this class? How do you plan to deal with lifetime issues? Carefully? Yuck. If you really want to use a "reference", use a smart pointer. – Chad Mar 15 '12 at 15:45

2 Answers2

2
class foo {
public:
  // See http://cdecl.ridiculousfish.com/?q=double+%28%26arr%29%5B3%5D%5B4%5D
  foo(double (&arr)[3][4]) :arr2(&arr) {
    // This constructor uses constructor list initialization, but you could have used
    // assignment instead, like this:
    // arr2 = &arr;
  }
  double bar() { //Usage
    double doSomething = (*arr2)[1][0];
    return doSomething*doSomething;
  }
private:
  // See http://cdecl.ridiculousfish.com/?q=double+%28*arr2%29%5B3%5D%5B4%5D
  double (*arr2)[3][4];
};

int main () {
  double oof[3][4] = {{0.,},};
  foo moo(oof);
  return int(moo.bar());
}
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
1

Since you don't specify a reason for using raw pointers and this is tagged C++, you should use nested vectors instead:

#include <vector>

class foo
{
public:

  void foo(const std::vector<std::vector<double>>& arr)
     : arr2(arr)
  { //Constructor
  }

  void bar() { //Usage
    double doSomething = arr2[1][0];
  }

private:
  std::vector<std::vector<double>> arr2;
};
Chad
  • 18,706
  • 4
  • 46
  • 63