473,569 Members | 2,352 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Returning an array?

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
multidimensiona l 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

Jul 22 '05 #1
19 1925
Steven T. Hatton wrote:
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
multidimensiona l 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
Jul 22 '05 #2

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

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

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

-JKop
Jul 22 '05 #3
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
Jul 22 '05 #4

"JKop" <NU**@NULL.NULL > wrote in message
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
Jul 22 '05 #5

"JKop" <NU**@NULL.NULL > wrote in message
news:vx******** ***********@new s.indigo.ie...
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
Jul 22 '05 #6
Sharad Kala posted:

"JKop" <NU**@NULL.NULL > wrote in message
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
Jul 22 '05 #7
Sharad Kala posted:

"JKop" <NU**@NULL.NULL > wrote in message
news:vx******** ***********@new s.indigo.ie...
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
Jul 22 '05 #8
Victor Bazarov wrote:
Steven T. Hatton wrote:
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[i][j] == m[j][i];

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

Jul 22 '05 #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)


Try

void print(unsigned rowSize, float blah[3]);
-JKop
Jul 22 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
14011
by: Krackers | last post by:
How do you write a function which returns a reference to an array. I can only get a function to return a copy of the array itself. I've had a look at some other threads in this group an the return value of a function acts like 'by Val' returning the value only (except for objects) can you make it return a reference instead? cheers, Krackers
7
7285
by: BrianJones | last post by:
Hi, if you have a function, how is it possible to return an array? E.g.: unsigned long function(...) // what I want to do, obviously illegal I do know such would be possible by using a dynamic array e.g: array *a; a = function(...)
10
10271
by: Fraser Ross | last post by:
I need to know the syntax for writing a reference of an array. I haven't seen it done often. I have a class with a member array and I want a member function to return an reference to it. Returning a pointer to the first element might do but I want to do what I've said. Fraser.
41
3771
by: Materialised | last post by:
I am writing a simple function to initialise 3 variables to pesudo random numbers. I have a function which is as follows int randomise( int x, int y, intz) { srand((unsigned)time(NULL)); x = rand(); y = rand();
3
2680
by: Faustino Dina | last post by:
Hi, The following code is from an article published in Informit.com at http://www.informit.com/guides/content.asp?g=dotnet&seqNum=142. The problem is the author says it is not a good idea to return an array as a property because it will return a copy of the array instead a reference to it. How can I force the property to return a reference...
5
19572
by: Stacey Levine | last post by:
I have a webservice that I wanted to return an ArrayList..Well the service compiles and runs when I have the output defined as ArrayList, but the WSDL defines the output as an Object so I was having a problem in the calling program. I searched online and found suggestions that I return an Array instead so I modified my code (below) to return...
17
3226
by: I.M. !Knuth | last post by:
Hi. I'm more-or-less a C newbie. I thought I had pointers under control until I started goofing around with this: ================================================================================ /* A function that returns a pointer-of-arrays to the calling function. */ #include <stdio.h> int *pfunc(void);
13
2540
by: Karl Groves | last post by:
I'm missing something very obvious, but it is getting late and I've stared at it too long. TIA for responses I am writing a basic function (listed at the bottom of this post) that returns data from a query into an array. The intent is that the following code:
0
4080
by: anuptosh | last post by:
Hi, I have been trying to run the below example to get a Oracle Array as an output from a Java code. This is an example I have found on the web. But, the expected result is that the code should return me Array element type code 1, but it is returning me type code 12 and the array in a junk or unreadable format . Our environment is JDK 1.4,...
5
2672
by: ctj951 | last post by:
I have a very specific question about a language issue that I was hoping to get an answer to. If you allocate a structure that contains an array as a local variable inside a function and return that structure, is this valid? As shown in the code below I am allocating the structure in the function and then returning the structure. I know...
0
7703
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7982
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6286
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5222
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3656
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3644
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2116
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1226
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
944
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.