Message: Re: How to return multi-dim arrays? Not Logged In (login)
 Next-in-Thread Next-in-Thread
 Next-in-Forum Next-in-Forum

None Re: How to return multi-dim arrays? 

Keywords: multidimensional array, return value, member function, type definition
Forum: Analysis
Re: Question How to return multi-dim arrays? (Matthias Boehm)
Date: 14 Jan, 2005
From: John Allison <John Allison>

The syntax is very tricky. It's a C heritage. Generally I recommend moving to std::vector - see below - but this too gets tricky for multidimensions.

But if you need to stay with arrays, the only way I could think of is to declare a typedef to a 2-D array [10][30] and return a pointer to that. The compiler (and you) need to know the dimensionality of all except the left (most slowly changing in terms of memory access). It's a logical problem of giving enough information to allow the compiler to know where to find x[1][2][3]. Arrays are passed as pointers; in this case a pointer to an array of arrays of [10][30].

Cheers, John.

 #include <iostream>

 double     depESum[11][10][30];
 double     depESum_1[11];

 typedef double two[10][30];

 double* GetDepESum_1()  {
    return depESum_1;
 };           // returns pointer to the 1D array
 //  works fine.

 two* GetDepESum() {
   depESum[1][2][3] = 55.;
   return depESum;
 };   // returns pointer to the 3-D array

 using namespace std;

 main() {
   two* x = GetDepESum();
   cout << x[1][2][3] << endl;

 #include <vector>
 #include <iostream>

 //double     depESum[11][10][30];
 typedef std::vector<double> one;
 typedef std::vector<std::vector<double> > two;
 typedef std::vector<std::vector<std::vector<double> > > three;
 three depESum(11);

 three* GetDepESum() {
   one a(30);  // A vector of 30 doubles.  (You would need 300 of these 
          	    // to fill the array.)
  a[3] = 55.; // Set 4th element.  (Note other elements not set, or
	      // rather, are set to an empty vector of doubles, so
	      // attempts to access them will cause error.)
   two b(10);  // A vector of 10 vectors of doubles.  (10 needed.)
   b[2] = a;   // Set 3rd element to contain a vector of 30 doubles.
   depESum[1] = b;
   return &depESum;
 };   // returns pointer to the 3-D array

 main() {
   three* x = GetDepESum();
   std::cout << (*x)[1][2][3] << std::endl;

Inline Depth:
 1 1
 All All
Outline Depth:
 1 1
 2 2
 All All
Add message: (add)

1 None: Re: How to return multi-dim arrays?   (John Allison - 14 Jan, 2005)
(_ None: Re: How to return multi-dim arrays?   (Jeremy McCormick - 14 Jan, 2005)
 Add Message Add Message
to: "Re: How to return multi-dim arrays?"

 Subscribe Subscribe

This site runs SLAC HyperNews version 1.11-slac-98, derived from the original HyperNews

[ Geant 4 Home | Geant 4 HyperNews | Search | Request New Forum | Feedback ]