I'm having this problem for quite a long time - I have fixed sized 2D array as a class member.
class myClass
{
public:
void getpointeM(...??????...);
double * retpointM();
private:
double M[3][3];
};
int main()
{
myClass moo;
double *A[3][3];
moo.getpointM( A ); ???
A = moo.retpointM(); ???
}
I'd like to pass pointer to M
matrix outside. It's probably very simple, but I just can't find the proper combination of &
and *
etc.
Thanks for help.
double *A[3][3];
is a 2-dimensional array ofdouble *
s. You wantdouble (*A)[3][3];
.Then, note that
A
and*A
and**A
all have the same address, just different types.Making a typedef can simplify things:
This being C++, you should pass the variable by reference, not pointer:
Now you don't need to use parens in type names, and the compiler makes sure you're passing an array of the correct size.
The short answer is that you can get a
double *
to the start of the array:Outside the class, though, you can't really trivially turn the
double *
into another 2D array directly, at least not in a pattern that I've seen used.You could create a 2D array in main, though (double A[3][3]) and pass that in to a getPoint method, which could copy the values into the passed-in array. That would give you a copy, which might be what you want (instead of the original, modifiable, data). Downside is that you have to copy it, of course.
Make M public instead of private. Since you want to allow access to M through a pointer, M is not encapsulated anyway.
I would, in general, prefer R over A because the all of the lengths are fixed (A could potentially point to a
double[10][3]
if that was a requirement) and the reference will usually lead to clearer code.In your
main()
function:creates a 3x3 array of
double*
(or pointers to doubles). In other words, 9 x 32-bit contiguous words of memory to store 9 memory pointers.There's no need to make a copy of this array in
main()
unless the class is going to be destroyed, and you still want to access this information. Instead, you can simply return a pointer to the start of this member array.If you only want to return a pointer to an internal class member, you only really need a single pointer value in
main()
:But, if you're passing this pointer to a function and you need the function to update its value, you need a double pointer (which will allow the function to return the real pointer value back to the caller:
And inside
getpointM()
you can simply point A to the internal member (M
):Your intent is not clear. What is
getpointeM
supposed to do? Return a pointer to the internal matrix (through the parameter), or return a copy of the matrix?To return a pointer, you can do this
For
retpointM
the declaration would look as followsThis is rather difficult to read though. You can make it look a lot clearer if you use a typedef-name for your array type
In that case the above examples will transform into