Returning an array?

  • Thread starter Steven T. Hatton
  • Start date
S

Steven T. Hatton

I believe it is technically possible to return a pointer to the first
element of an array. I can persuade the returned pointer to act like an
array, with some qualifications. I'm specifically interested in
multidimensional arrays.

It is often said that arrays and pointers are virtually identical. My
observations are that my (gcc) compiler knows the difference between T*, T
a1[9], and a2[3][3].

What I'm currently trying to do is to return a pointer (or reference) to an
array which was passed in as a container for the results of matrix
calculations taking two other matrices as arguments. It's the same concept
as using ostream& print(&ostream out, const objType& obj){ out << obj.data;
return out; }. I don't absolutely /need/ the functionality, but it would
be more intuitive to work with in some instances.

AFAIK, there is no way to specify an array return type. Whereas I can
specify 'ostream&', I cannot specify 'T[][dimensions]' as a return type. I
can use 'T*' as the return type and cast the returned array to T*. But
then it's not the same type as was passed in. Not to mention that it is
rather tricky playing with arrays at that level.

There are various reasons I would rather not use the stl containers. I can
create my own containers. AAMOF, that's what I'm doing. I don't need nor
even want iterators. Is wrapping the array in some kind of class type
object the only viable approach to passing arrays around?
--
"If our hypothesis is about anything and not about some one or more
particular things, then our deductions constitute mathematics. Thus
mathematics may be defined as the subject in which we never know what we
are talking about, nor whether what we are saying is true." - Bertrand
Russell
 
V

Victor Bazarov

Steven said:
I believe it is technically possible to return a pointer to the first
element of an array.

Yes, it is possible.
I can persuade the returned pointer to act like an
array, with some qualifications. I'm specifically interested in
multidimensional arrays.

It is often said that arrays and pointers are virtually identical. My
observations are that my (gcc) compiler knows the difference between T*, T
a1[9], and a2[3][3].

They are not the same type, if that's what you're alluding to.
What I'm currently trying to do is to return a pointer (or reference) to an
array which was passed in as a container for the results of matrix
calculations taking two other matrices as arguments. It's the same concept
as using ostream& print(&ostream out, const objType& obj){ out << obj.data;
return out; }. I don't absolutely /need/ the functionality, but it would
be more intuitive to work with in some instances.

"Intuitive" is not really objective. But if it's intuitive to you,
by all means, do it.
AFAIK, there is no way to specify an array return type. Whereas I can
specify 'ostream&', I cannot specify 'T[][dimensions]' as a return type. I
can use 'T*' as the return type and cast the returned array to T*. But
then it's not the same type as was passed in. Not to mention that it is
rather tricky playing with arrays at that level.

There are various reasons I would rather not use the stl containers. I can
create my own containers. AAMOF, that's what I'm doing. I don't need nor
even want iterators. Is wrapping the array in some kind of class type
object the only viable approach to passing arrays around?

Yes, actually. That's a very common approach. Wrapping it in a struct
is the simplest thing, and has worked for generations of C programmers.

You could, of course, try to work with _references_ to arrays, but the
syntax is really convoluted, to say the least. Although, you coudl get
around it with some typedefs...

typedef double (&dMatrix3x3)[3][3];

dMatrix3x3 mul(dMatrix3x3 m, double d)
{
m[0][0] *= d; m[0][1] *= d; m[0][2] *= d;
m[1][0] *= d; m[1][1] *= d; m[1][2] *= d;
m[2][0] *= d; m[2][1] *= d; m[2][2] *= d;
return m;
}

int main()
{
double m[3][3] = { 1,2,3,4,5,6,7,8,9 };
mul(mul(m, 2), 5);

// m should now contain { 10,20,30 ...
}

V
 
J

JKop

int* Blah()
{
int monkey[12];

return monkey;
}


int main()
{
int* const &poo = Blah();

poo[2] = 3; //UB: The array no longer exists
}

-JKop
 
J

JKop

You could, of course, try to work with _references_ to arrays, but the
syntax is really convoluted, to say the least.


I disagree. It's simple operator and operand precedence:


int &k[5]; //an array of 5 references to integers

int (&k)[5]; //a reference to an array of 5 integers


-JKop
 
S

Sharad Kala

JKop said:
int &k[5]; //an array of 5 references to integers

Never knew that array of references are legal! Have you ever tried to
compile this code ?

Sharad
 
S

Sharad Kala

int (&k)[5]; //a reference to an array of 5 integers

This too is illegal. You need to initialize the reference, i.e. it has to be
bound to something for sure.

Sharad
 
J

JKop

Sharad Kala posted:
JKop said:
int &k[5]; //an array of 5 references to integers

Never knew that array of references are legal! Have you ever tried to
compile this code ?

Sharad


You're correct, there can't be an array of references.

But... my syntax above *would* define such if it were legal... (ie. I have
the correct operator precedence)


-JKop
 
J

JKop

Sharad Kala posted:
int (&k)[5]; //a reference to an array of 5 integers

This too is illegal. You need to initialize the reference, i.e. it has
to be bound to something for sure.

Sharad

int main()
{
int poo[5];

int (&blah)[5] = poo;
}


-JKop
 
S

Steven T. Hatton

Victor said:
Steven said:
It is often said that arrays and pointers are virtually identical. My
observations are that my (gcc) compiler knows the difference between T*,
T a1[9], and a2[3][3].

They are not the same type, if that's what you're alluding to.

Yes, that's pretty much what I had intended. I should have waited until I
got some sleep before sending this. (I actually figured it out before I
went to bed. Nonetheless...). I had simply been passing the wrong things
to my functions.

float m[3][3] = {{1,2,3},{4,5,6},{7,8,9}};

// this doesn't work:
void print(unsigned rowSize, float* mat[]){/*...*/}
error: cannot convert `float (*)[3]' to `float**' for argument `2'
to `void print(unsigned int, float**)'

// nor does this:
void print(unsigned rowSize, float** mat){/*...*/}
error: cannot convert `float (*)[3]' to `float**' for argument `2'
to `void print(unsigned int, float**)'

// Now, this lovely bit of hackerie *does* work

void print(unsigned rowSize, float* mat00)
{
float** mat = &mat00;

unsigned size = rowSize * rowSize;
// perhaps size_t would be more correct than unsigned?

cout << "\n---------- matrix mat** -----------\n";
for(unsigned i = 0; i < size; i++)
{
if(i%rowSize == 0 && i != 0){cout<<"\n";}
cout << setw(4) << *(*(mat + i/size ) + i%size) <<" ";
}
cout << "\n";
}

float m[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
print(3, &m[0][0]);
"Intuitive" is not really objective. But if it's intuitive to you,
by all means, do it.

I believe there are other advantages as well. I have not experimented with
it, but I should be able to chain operations together in a single
expression this way.
create my own containers. AAMOF, that's what I'm doing. I don't need
nor even want iterators. Is wrapping the array in some kind of class type
object the only viable approach to passing arrays around?

Yes, actually. That's a very common approach. Wrapping it in a struct
is the simplest thing, and has worked for generations of C programmers.

You could, of course, try to work with _references_ to arrays, but the
syntax is really convoluted, to say the least. Although, you coudl get
around it with some typedefs...

typedef double (&dMatrix3x3)[3][3];

I believe that's the/an answer I was fishing for. The obvious problem with
pointers, references and arrays is that of discriminating between a pointer
to an array and an array of pointers. Likewise for references.

BTW. I tried to figure out if it was meaningful to create an array of
references to the elements of another array. For example,
float m[3][3];
float& ref_m[3][3]; // somehow make ref_m[j] == m[j];

I concluded that this could not be done. Am I correct?

--
"If our hypothesis is about anything and not about some one or more
particular things, then our deductions constitute mathematics. Thus
mathematics may be defined as the subject in which we never know what we
are talking about, nor whether what we are saying is true." - Bertrand
Russell
 
J

JKop

// this doesn't work:
void print(unsigned rowSize, float* mat[]){/*...*/}
error: cannot convert `float (*)[3]' to `float**' for argument `2'
to `void print(unsigned int, float**)'

// nor does this:
void print(unsigned rowSize, float** mat){/*...*/}
error: cannot convert `float (*)[3]' to `float**' for argument `2'
to `void print(unsigned int, float**)'

// Now, this lovely bit of hackerie *does* work

void print(unsigned rowSize, float* mat00)

Try

void print(unsigned rowSize, float blah[3]);


-JKop
 
S

Steven T. Hatton

Steven said:
cout << "\n---------- matrix mat** -----------\n";
for(unsigned i = 0; i < size; i++)
{
if(i%rowSize == 0 && i != 0){cout<<"\n";}
cout << setw(4) << *(*(mat + i/size ) + i%size) <<" ";
the i/size and i%size can be replace with one i. These were carried over
from another form of the function that required them.
--
"If our hypothesis is about anything and not about some one or more
particular things, then our deductions constitute mathematics. Thus
mathematics may be defined as the subject in which we never know what we
are talking about, nor whether what we are saying is true." - Bertrand
Russell
 
V

Victor Bazarov

Steven said:
[...]
BTW. I tried to figure out if it was meaningful to create an array of
references to the elements of another array. For example,
float m[3][3];
float& ref_m[3][3]; // somehow make ref_m[j] == m[j];

I concluded that this could not be done. Am I correct?


You cannot have an array of references. You can, however, have
a reference to an array (as you saw). You can wrap your reference
in a struct and have an array of that struct:

template<class T> struct ref {
T &d;
ref(T &d) : d(d) {}
};

The problem, however, is in initialising it. You would have to
intialise the elements of that array all manually:

float m[3][3];
ref<float> rm[3][3] = { { m[0][0], m[0],[1] ...

so I don't think it's a viable alternative.

Victor
 
S

Steven T. Hatton

Victor said:
Steven said:
[...]
BTW. I tried to figure out if it was meaningful to create an array of
references to the elements of another array. For example,
float m[3][3];
float& ref_m[3][3]; // somehow make ref_m[j] == m[j];

I concluded that this could not be done. Am I correct?


You cannot have an array of references. You can, however, have
a reference to an array (as you saw). You can wrap your reference
in a struct and have an array of that struct:

template<class T> struct ref {
T &d;
ref(T &d) : d(d) {}
};

The problem, however, is in initialising it. You would have to
intialise the elements of that array all manually:

float m[3][3];
ref<float> rm[3][3] = { { m[0][0], m[0],[1] ...

so I don't think it's a viable alternative.

Victor


I don't believe that's any better than using an array of pointers. Unless
I'm missing something, you would have to access the data as rm[j].d
wouldn't you? What I was shooting for was something that acted just like
the array, but was indexed as it's transpose. For now, I don't have a use
for it because I took a different approach to solving the immediate
problem.

I do however have another question along these lines.

This works:

template < unsigned REMAINING, unsigned ORDER, typename T1, typename T2,
typename OP>
class Array2OpAssign {
public:
typedef T1 (&rank1T1)[ORDER];
typedef T1 (&rank1T2)[ORDER];

static rank1T1 result(rank1T1 a1, const rank1T2 a2) {
OP op;
a1[ORDER - REMAINING] = op(a1[ORDER - REMAINING], a2[ORDER - REMAINING]);
return Array2OpAssign<REMAINING - 1, ORDER, T1, T2, OP>::result(a1,a2);
}
};


However, this doesn't:

template <unsigned ORDER, typename T1, typename T2>
typedef T1 (&rank1T1)[ORDER]; // this ain't legal
typedef T1 (&rank1T2)[ORDER];
inline rank1T1 array2PlusAssign( rank1T1 a1, const rank1T2 a2)
{
return Array2OpAssign<ORDER,ORDER, T1, T2, Plus<T1, T2> >::result(a1,
a2);
}

perhaps playing with typedefs on the calling end is the way to go. I don't
particularly like that idea. It's much nicer to have a clean convenience
function that invokes the static function on the Array2OpAssign. Any
suggestions on how to template that typedef for a function template return
type?

--
"If our hypothesis is about anything and not about some one or more
particular things, then our deductions constitute mathematics. Thus
mathematics may be defined as the subject in which we never know what we
are talking about, nor whether what we are saying is true." - Bertrand
Russell
 
S

Steven T. Hatton

JKop said:
You could, of course, try to work with _references_ to arrays, but the
syntax is really convoluted, to say the least.


I disagree. It's simple operator and operand precedence:


int &k[5]; //an array of 5 references to integers

int (&k)[5]; //a reference to an array of 5 integers


-JKop

template <unsigned ORDER, typename T1, typename T2 >
T1 (&array2PlusAssign(T1(&t1)[ORDER], T2(&t2)[ORDER]))[ORDER]

That's f'ing psycho! Convoluted it far too kind!

Oh, and try setting the second parameter to const.

--
"If our hypothesis is about anything and not about some one or more
particular things, then our deductions constitute mathematics. Thus
mathematics may be defined as the subject in which we never know what we
are talking about, nor whether what we are saying is true." - Bertrand
Russell
 
V

Victor Bazarov

Steven T. Hatton said:
Victor said:
Steven said:
[...]
BTW. I tried to figure out if it was meaningful to create an array of
references to the elements of another array. For example,
float m[3][3];
float& ref_m[3][3]; // somehow make ref_m[j] == m[j];

I concluded that this could not be done. Am I correct?


You cannot have an array of references. You can, however, have
a reference to an array (as you saw). You can wrap your reference
in a struct and have an array of that struct:

template<class T> struct ref {
T &d;
ref(T &d) : d(d) {}
};

The problem, however, is in initialising it. You would have to
intialise the elements of that array all manually:

float m[3][3];
ref<float> rm[3][3] = { { m[0][0], m[0],[1] ...

so I don't think it's a viable alternative.

Victor


I don't believe that's any better than using an array of pointers. Unless
I'm missing something, you would have to access the data as rm[j].d
wouldn't you?


You could just add

operator T () const;
operator T& ();

to the struct and you don't need .d any more, AFAIUI.
What I was shooting for was something that acted just like
the array, but was indexed as it's transpose. For now, I don't have a use
for it because I took a different approach to solving the immediate
problem.
Whatever.


I do however have another question along these lines.

This works:

template < unsigned REMAINING, unsigned ORDER, typename T1, typename T2,
typename OP>
class Array2OpAssign {
public:
typedef T1 (&rank1T1)[ORDER];
typedef T1 (&rank1T2)[ORDER];

static rank1T1 result(rank1T1 a1, const rank1T2 a2) {
OP op;
a1[ORDER - REMAINING] = op(a1[ORDER - REMAINING], a2[ORDER -
REMAINING]);
return Array2OpAssign<REMAINING - 1, ORDER, T1, T2,
OP>::result(a1,a2);
}
};


However, this doesn't:

template <unsigned ORDER, typename T1, typename T2>
typedef T1 (&rank1T1)[ORDER]; // this ain't legal

Nonsense. Why ain't it legal?
typedef T1 (&rank1T2)[ORDER];
inline rank1T1 array2PlusAssign( rank1T1 a1, const rank1T2 a2)
{
return Array2OpAssign<ORDER,ORDER, T1, T2, Plus<T1, T2> >::result(a1,
a2);
}

perhaps playing with typedefs on the calling end is the way to go. I
don't
particularly like that idea. It's much nicer to have a clean convenience
function that invokes the static function on the Array2OpAssign. Any
suggestions on how to template that typedef for a function template return
type?

I have no idea what you're talking about. This compiles just fine
(as it should, of course):

template<unsigned U, typename T> class C {
typedef T (&Tarrref);
public:
C();
void foo(Tarrref r);
};

int main() {
C<5,int> c;
int a[5];
c.foo(a);
}

Victor
 
S

Steven T. Hatton

Victor said:
Steven T. Hatton said:
I don't believe that's any better than using an array of pointers. Unless
I'm missing something, you would have to access the data as rm[j].d
wouldn't you?


You could just add

operator T () const;
operator T& ();

to the struct and you don't need .d any more, AFAIUI.


I believe that will work. I need to give it a whack. I did something like
that for a similar situation last night and it worked. I had forgotten
about type conversion operators. Good call!
Whatever.

But it /is/ nice to know I can do it. Now that I see that I probably /can/
make a transpose pointer matrix act like a normal matrix, that opens a lot
of possibilities. It's much easier to think about orthogonal
transformations and the like when I can use (almost) real transpose
(inverse) matrices rather than simulating them by dancing around with the
indeces.
template <unsigned ORDER, typename T1, typename T2>
typedef T1 (&rank1T1)[ORDER]; // this ain't legal

Nonsense. Why ain't it legal?

Look at it again.
typedef T1 (&rank1T2)[ORDER];
inline rank1T1 array2PlusAssign( rank1T1 a1, const rank1T2 a2)
{
return Array2OpAssign said:
::result(a1,
a2);
}

perhaps playing with typedefs on the calling end is the way to go. I
don't
particularly like that idea. It's much nicer to have a clean convenience
function that invokes the static function on the Array2OpAssign. Any
suggestions on how to template that typedef for a function template
return type?

I have no idea what you're talking about. This compiles just fine
(as it should, of course):

template<unsigned U, typename T> class C {
typedef T (&Tarrref);
public:
C();
void foo(Tarrref r);
};


I tend to write:
template<unsigned U, typename T>
class C {
/*...*/
};

It avoids confusion. ;)

--
"If our hypothesis is about anything and not about some one or more
particular things, then our deductions constitute mathematics. Thus
mathematics may be defined as the subject in which we never know what we
are talking about, nor whether what we are saying is true." - Bertrand
Russell
 
S

Steven T. Hatton

Victor said:
Steven T. Hatton said:
Victor said:
template <unsigned ORDER, typename T1, typename T2>
typedef T1 (&rank1T1)[ORDER]; // this ain't legal

Nonsense. Why ain't it legal?

Look at it again.

Stop playing games and state your opinion.
#include <iostream>
#include <string>

template <typename T>
typedef T Tfoo;
T foo(T& tf){return tf;}

int main()
{
std::string bar = "This is foo.\n";
std::cout << foo(bar);
}
//--------------EOF----------------
hattons@ljosalfr:~/code/c++/scratch/typedef/
Mon Oct 11 01:08:18:> g++ -ofoo main.cc
main.cc:5: error: template declaration of `typedef T Tfoo'
main.cc:6: error: `T' was not declared in this scope
main.cc:6: error: `tf' was not declared in this scope
main.cc:6: error: syntax error before `{' token
main.cc: In function `int main()':
main.cc:11: error: `foo' undeclared (first use this function)
main.cc:11: error: (Each undeclared identifier is reported only once for
each
function it appears in.)
hattons@ljosalfr:~/code/c++/scratch/typedef/
Mon Oct 11 01:08:19:>

#include <iostream>
#include <string>

template <typename T>
//typedef T Tfoo;
T foo(T& tf){return tf;}

int main()
{
std::string bar = "This is foo\n";
std::cout<< foo(bar);
}
//--------------EOF----------------

hattons@ljosalfr:~/code/c++/scratch/typedef/
Mon Oct 11 01:08:29:> g++ -ofoo main.cc
You have new mail in /var/spool/mail/hattons
hattons@ljosalfr:~/code/c++/scratch/typedef/
Mon Oct 11 01:15:04:>

It's a function template not a class template. You can put a typedef there.

foo
--
"If our hypothesis is about anything and not about some one or more
particular things, then our deductions constitute mathematics. Thus
mathematics may be defined as the subject in which we never know what we
are talking about, nor whether what we are saying is true." - Bertrand
Russell
 
V

Victor Bazarov

Steven said:
[..]
template <unsigned ORDER, typename T1, typename T2 >
T1 (&array2PlusAssign(T1(&t1)[ORDER], T2(&t2)[ORDER]))[ORDER]

That's f'ing psycho! Convoluted it far too kind!

Oh, and try setting the second parameter to const.

References themselves cannot be set to const because they are not
objects. You _can_ make 'T2' const:

template <unsigned ORDER, typename T1, typename T2 >
T1 (&a2PA(T1(&t1)[ORDER], T2 const(&t2)[ORDER]))[ORDER]
.. ^^^^^

V
 
V

Victor Bazarov

Steven said:
Victor Bazarov wrote:

Steven T. Hatton said:
Victor Bazarov wrote:


[...]

template <unsigned ORDER, typename T1, typename T2>
typedef T1 (&rank1T1)[ORDER]; // this ain't legal

Nonsense. Why ain't it legal?

Look at it again.

Stop playing games and state your opinion.

It's a function template not a class template. You can put a typedef there.

I missed the fact that you decided to make it stand-alone function.
My impression was that you were talking about replacing the body of
the class definition with that other code. Apologies.

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,989
Messages
2,570,207
Members
46,783
Latest member
RickeyDort

Latest Threads

Top