Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get array from object in c++

This question might be simple but I never use raw pointers or arrays in C++ so...

I need to use a library function which looks like this:

void f(double a[3][3], double b[3], double c[3]);

a and b are used for input and the result is stored in c.

The computation of a is a bit complex but does never change so it makes sense to calculate it only once and save the result. In my program, I can link it to an object of type X.

class X{
public:
X(){ 
    a = {{1,2,3},
         {4,5,6},
         {7,8,9}}; 
    }

private:
    double a[3][3];
}

How can I write a getter for X::a which can be used in function f?

This is how I would like to call function f:

#include "X.h"

int main(int argc, char *argv[]){

    X o = X(); //create object
    double a[3][3] = o.getA(); // I want to get a somehow
    double b[3] =  {1,2,3}; // create dummy b
    double c[3] = {}; // create empty c
    f(a,b,c); // call funktion to populate c
    for(int i=0; i<3; ++i){
        std::cout << c[i] << endl;
    }
}
like image 552
user7431005 Avatar asked Feb 13 '26 18:02

user7431005


1 Answers

You know std::vector is the way to go for 2D arrays in C++, but if you can't bypass the obstacle you are facing, then it would be possible to pass the matrix as a parameter to the getter function, like this:

#include <iostream>

class X {
 public:
    void getA(double (&array)[3][3]) {
        for (int i = 0; i < 3; ++i)
            for (int j = 0; j < 3; ++j)
                array[i][j] = a[i][j];
    }
 private:
    double a[3][3] = {{1,2,3},
            {4,5,6},
            {7,8,9}};
};

int main(void) {
    X o = X();
    double a[3][3];
    o.getA(a);
    for(int i = 0; i < 3; ++i)
        for(int j = 0; j < 3; ++j)
            std::cout << a[i][j] << std::endl;
    return 0;
}
like image 200
gsamaras Avatar answered Feb 15 '26 07:02

gsamaras



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!