• 13
• 27
• 9
• 9
• 20

# Returning Arrays

This topic is 4398 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I want to fill an array in a function and then pass that array out of the function. For instance:
int function()
{
start_num=5;
range = 5;
for(i=0;i<range;i++)
{
array=start_num;
start_num++;
}
return array;
}


What I expect this function to do is: Assign values to each slot in the array (5,6,7,8,9) Then return the array so I can use it like a normal array in another function How would I do that? do I have to return a pointer to the array? If so am I then assigning the return value of the function to a pointer? Or if I return the array do I assign it to another array? This is a project for school so if you want more information: http://www.cs.umbc.edu/courses/undergraduate/201/spring06/projects/p1/ THe precise function I'm working with is int GetValidInt(int min, int max); // gets an integer from the user between min and max, inclusive and returns that valid integer. I'm guessing what they wanted was to loop that function and return a single value each time but I'm thinking this way I don't have to loop that function and just get all my values at one time.

##### Share on other sites
What language?

In C++, Java and C#, arrays (vectors for C++) can be returned like any other object.

##### Share on other sites
Normally, "gets an integer from the user" means that the user has to type in a number (an integer in this case). IMHO you have to write the function to prompt the user for a number, read in the user's typed input, interpret that as an integer number, and check that the number is in the specified range. Let the function repeat its body until a valid number is available. Then return that number. I don't see an array as you've described anywhere in that function.

EDIT: Please notice that the exercise prescribes the function prototypes. So one is neither allowed to alter the arguments nor to alter the type of return value.

Notice furthurmore this extract from the exercise text:
Quote:

I think that supports my opinion.

##### Share on other sites
you don't need to actually return the array.
the array should be a function parameter.

call your function like this: function(array);

int function(int array[])
{

##### Share on other sites
sorry, you need to make the funtion type "void"
because now you won't actually return something.

void function(int array[])
{

##### Share on other sites
One answer to your question about how to pass in and fill out an array is to use the similarity between arrays and pointers:

#include <stdio.h>void function ( int *pArray, int numElements ){	if ( NULL == pArray )		return;	int start_num = 5;	for ( int i = 0; i < numElements; ++i )	{		pArray[ i ] = start_num;		start_num++;	}}void main ( void ){	int myArray[ 5 ];	function ( myArray, 5 );}

In this case it is wise to pass not only a pointer to the array but also the size of the array (e.g., the number of elements in the array) so that you know how many elements to loop over in your for loop.

Hope this helps!

##### Share on other sites
What language?
C++

I don't see an array as you've described anywhere in that function.

I'd be changing the contents of the function - the original design doesn't expect you to make an array

void function(int array[])
{

That assumes there was a pre-made array. The function I was thinking about creates an array with contents defined by the two values (min and max) that the user enters.

NOTE: I left information out because my question was sort of generalized and I didn't think I needed to give people full detail (I am supposed to do this project by myself I just wanted clarification on that point)

Sanity Assassin's post (Sorry too lazy to quote it)
So your saying if I create the array and pass a pointer then that would modify the original array and I wouldn't need to return anything.

While I think that's the best way to do that - I can't modify the preset function prototype for my project.

I guess i have no choice but to use a loop. -- WOW

Okay I see what haegarr is saying. I don't actually use GetValidInt to define my range of integers or values that I'm computing I just use it to determine wheter or not the user's values are within the range 1 - 100000. And if they are negative convert to positive. - That changes a bit of the intial code around.

Thanks everyone for the input.

##### Share on other sites
Quote:
 Original post by PSWindOkay I see what haegarr is saying. I don't actually use GetValidInt to define my range of integers or values that I'm computing I just use it to determine wheter or not the user's values are within the range 1 - 100000. And if they are negative convert to positive. - That changes a bit of the intial code around.

Not exactly. The minimum is not always 1 and the maximum not always 100000! The function gets the minimum and maximum specified as parameters! Every integer value inside that range is allowed, even negative numbers (as long as the context doesn't hide them). Please look at the signature of the function carefully:
Quote:
 int GetValidInt (int min, int max); -- gets an integer from the user between min and max, inclusive and returns that valid integer.

There is definitely stated that any integer between the min and max inclusive is allowed. If e.g. min is -100 and max is +100 then the function is defined to accept e.g. a -10, since -100 <= -10 <= +100.

Notice furthur that the cited function also not only validates the number but reads it in! This is necessary since the number isn't passed by argument, and the exercise does not allow to change the function's signature.

##### Share on other sites
*** If you don't like explanations and just want advice, scroll down to the horizontal bar. But shame on you for not taking the opportunity to understand better. ***

Arrays aren't real objects ("things") in C++ or C - that is to say, they're treated specially in a few ways, and you can't do everything with them that you might expect. Basically, they're evil.

If you are going to create "the array" as a new thing, then it would have to be something declared locally - otherwise you're limited to modifying outside stuff. But then, you can't just return a local array the same way you'd return a local int:

// NOT WORKING CODEint[5] function() {  int local[5];  // do stuff to the array  return local;}

There are two problems: First of all, you can't specify an array as a return type like that (and trying to return an array with the return type as "int" doesn't work either). The best you can do is return a pointer, which would be of type "pointer to int" and which points to the beginning of the array:

// STILL NOT WORKING, IN A MORE SUBTLE WAYint* function {  int local[5];  // do stuff to the array  return local; // Referring to an array by name, with no subscript, means  // a pointer to the beginning of the array.}

This gets past the compiler, but is still wrong at runtime - we are returning a pointer into memory that is cleaned up at the end of the function, so that as soon as the caller gets the pointer, that memory isn't "ours" any more, and technically anything could be there. That is, we have created "undefined behaviour". Worse yet, it might *seem* to work some of the time, making it a lot harder to debug.

Things are even more complicated with multi-dimensional arrays. First off, a statically declared array of multiple dimensions has to be rectangular, and the compiler makes use of that for optimization - it stores all the data in one chunk, making use of the known sizes in order to translate your multiple indexing into a single index. Oh, and the name by itself is now a pointer to *the chunk*, so the type is still (type of stored element)*, not (type of stored element)**.

Anyway. What you *would* need to do is allocate the memory dynamically, and then remember to deallocate it at an appropriate time. However, in C++ we can make that easier by creating a wrapper object that allocates in its constructor and deallocates in its destructor.

But we don't have to do even that, because the C++ standard library already provides an object that does all of that and more. Consider:

#include <vector>// WORKSstd::vector<int> function() {  std::vector<int> result(5); // the 5 here specifies the size, not any contents  // Put stuff into the vector here, using subscripting just as we would  // with an array  return result; // returns the actual object, not any kind of pointer  // and the data is all stored in memory that has an appropriate lifetime.}

There is more that you can do with vectors that you can't with arrays - in particular, you can resize them, append to the end and have the storage automatically grow accordingly, etc.

##### Share on other sites
Wow, i always thought arrays were just another type of variable. Very enlightening, would that make vectors, generally, a better choice than arrays?

Quote:
 Not exactly. The minimum is not always 1 and the maximum not always 100000! The function gets the minimum and maximum specified as parameters! Every integer value inside that range is allowed, even negative numbers (as long as the context doesn't hide them). Please look at the signature of the function carefully:

That I actually knew, I think you misunderstood me.

Quote:
 There is definitely stated that any integer between the min and max inclusive is allowed. If e.g. min is -100 and max is +100 then the function is defined to accept e.g. a -10, since -100 <= -10 <= +100.

True, but I was thinking within the scope of my project (which is over now) and all the numbers involved would be between the pre-defined MIN and MAX (1, 100000). I think I was wrong about converting to positive ints though.