return matrix in function

Dear all,

I have found a lot of solutions using Google but no solution did work.
Could you please tell me how we can return a 3x3 matrix in c++ function.

My code is:

1
2
3
4
5
6
7
8
double *computeA()
	{
		
		double *A = new double[2][2];
                // some operations on A and then return
		return A;

	}


The error that I have in this case is:

error C2440: 'initializing' : cannot convert from 'double (*)[2]' to 'double *'


Thank you in advance
Last edited on
The type of A should be double(*)[2] (pointer to array of 2 doubles).
1
2
3
4
5
6
double(*computeA())[2]
{
	double (*A)[2] = new double[2][2];
	// some operations on A and then return
	return A;
}

Don't forget to delete[] the pointer returned by the function when you are done with it.

If you want to avoid having to worry about delete[] you can use std::array and return the array by value.
1
2
3
4
5
6
std::array<std::array<double, 2>, 2> computeA()
{
	std::array<std::array<double, 2>, 2> A;
	// some operations on A and then return
	return A;
}
Thank you so much Peter87.

In the case of std::array<std::array<double, 2>, 2> A; which I prefer, how we can scan the elements? using iterator as the case in vector?
Iterators or by index like normal arrays.
Thank you ;)
Have a nice day.
For this simple code
1
2
3
4
5
6
7
8
9
10

#include <iostream>
#include <array>

int main()
{
	std::array<std::array<double, 3>, 3> X;
	system("PAUSE");
	return 0;
}


I've got this error:

main.cpp(6) : error C2039: 'array' : is not a member of 'std'
std::array was added in C++11 so maybe you have to turn on C++11 features somehow. If you are using GCC you can do that by passing -std=c++11 (or -std=c++0x) to the compiler.
I am using Visual c++ 2008.
Topic archived. No new replies allowed.