returning an array

Apr 8, 2010 at 2:38am
How can I write a function which takes an integer x and return the two-element array {x, x}?
Apr 8, 2010 at 2:46am
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include<iostream>

using namespace std;
using namespace System;

int* toarray(int x){
	int *thearray=new int[2];
	thearray[0]=thearray[1]=x;
	return thearray;

}

int main(array<System::String ^> ^args)
{
	int x=15;
	int* thearray=toarray(x);
	cout<<thearray[0]<<"  "<<thearray[1];
	return 0;
}
Apr 8, 2010 at 2:52am
closed account (1yR4jE8b)
You forgot to mention that doing if you do it this way you would need to delete the array when you are done with it.
Apr 8, 2010 at 3:08am
return make_pair(x, x);

Of course you need to have pairs and make it a template function, but I'll let you do that yourself. :)
Apr 8, 2010 at 3:56am
I don't like the idea of returning a pointer andjust saying "Yeah, it's an array with two elements".

How are you supposed to know how many elements it has? Yes, in this case, you know it has two, but I don't think you should do it like that. It looks like a recipe for segmentation faults to me.

I would do it with a vector:
std::vector <int> foo(int x);
or, you could "return" the value in an argument and return the number of elements as a return value, e.g.
1
2
3
4
5
int foo(int buffer[], int x)
{
        /* [...] */
        return number_of_elements;
}

but the first (vector) way is better.
Apr 8, 2010 at 5:04pm
I agree with chrisname. There are a number of solutions. I'm sure the OP is a simplification of the problem but sometimes I wonder why such a function would ever be needed in the first place. Constructing a std::vector in place is very simple so unless there is some complex algorithm for building the array and filling it I see no reason to have an additional function call.

1
2
3
4
5
6
7
8
// create a dynamic array in place.  Then there is no reason to worry about the issues
// with returning an array from a function.
int x = 5;
std::vector<int> buffer(x); 

// Even if you want a c-array it is fairly simple to do it in place.  Why bother calling a function
// just to create it and return a pointer?
int* buffer = new int[x];


This probably contains more info then you really need but it could give you examples on how to do things like this with template programming instead of c-arrays. Ultimately you can create arrays in place and then pass the array to a function so that it is filled. I just don't see the need for a function whose sole purpose is to create an empty array and return a pointer.

http://cplusplus.com/forum/articles/20881/
Topic archived. No new replies allowed.