Hey, I need to make a function that returns an array. How would I do so? And how would I make a variable that gets all the values in that function? Thanks, you guys :)

Hey, I need to make a function that returns an array. How would I do so? And how would I make a variable that gets all the values in that function? Thanks, you guys :)

Do you have tried any code? please post it.

> I need to make a function that returns an array.

There is no way to return an array from a function (in either C or C++).

You can return a pointer to the first element of a dynamically allocated memory (which is messy). You could return a reference to an array (but the size must be known at compile time and its life-time needs to be correctly managed).

The sensible thing to do would be to return a std::vector<>. See:
http://pages.cs.wisc.edu/~hasti/cs368/CppTutorial/NOTES/CLASSES-INTRO.html#vector
http://www.mochima.com/tutorials/vectors.html

@vijayan121

Thanks for sharing this. I knew about vectors, but didn't think about using them in functions.

#include <iostream>
#include <vector>

std::vector<int> lulz()
{
	std::vector<int> ie;
	for(int i = 0 ; i <= 10 ; i++)
		ie.push_back(i);
	return ie;
}

int main()
{
	std::vector<int> shoot = lulz();
	for(std::vector<int>::iterator it = shoot.begin() ; it != shoot.end() ; it++)
	{
		std::cout << *it << "\n";
	}

	std::cin.get();
}

The normal array is not returnable. You can use pointer array instead OR vector

type* func(int size) {
type *array = new type[size];
return array;
}

Edited 5 Years Ago by sergent: n/a

This article has been dead for over six months. Start a new discussion instead.