Reputation: 57
I'm new to C++ programming and i want to make a function that gives you all the common dividers into an array, and afterwards use it in int main()
Is returning an array from a function possible :D?
Thank you!
Code: http://pastebin.com/K8195wzF
Upvotes: 0
Views: 597
Reputation: 96790
Returning a dynamically-sized container like std::vector
has the best use case here:
#include <vector>
...
std::vector<int> dividers(int x, int y) {
std::vector<int> divi;
...
return divi;
}
Returning by value creates a copy, ensuring no dangling pointers. Such is the case when returning a local array through a pointer: the memory will be lost when the function exits leaving the pointer to point to garbage.
Upvotes: 4
Reputation: 2645
You could do the following:
typedef int arrT[10]
arrT *func() {}
whereby one is defining arrT to be an alias of an array of 10 ints or
int (*func())[10]{}
whereby one is defining func when dereferenced to return an array of 10 ints.
A using
declaration such that using arrT = int[10]
is also possible.
As others have noted, returning a std::vector from a function containing the type desired is possible with a function declared as std::vector<int> func(){}
.
Also, you could use another container std::array<>
and forget built-in arrays altogether.
Reference: C++ Primer; Lippman, Lajoie, Moo
Upvotes: -1
Reputation: 8027
No it's not possible. You could return a vector, or you could pass a pointer to the first element of an array to your function.
Looking at your code, the pointer option would look something like this
int dividers(int y,int x, int* divi){
...
}
int main()
{
int divi[100];
...
dividers(x, y, divi);
}
The vector solution might look like this
std::vector<int> dividers(int y,int x){
std::vector<int> divi;
...
divi.push_back(n); // when you want to add a divider to your vector
...
return divi;
}
int main()
{
std::vector<int> divi;
...
divi = dividers(x, y);
}
Upvotes: -1
Reputation: 19928
Yes it is possible to return an array in form of a pointer, but this is not recommended as you won't know its size in advance. But take care not to return the address of a local variable (allocated on the stack!!). Another problem with your code is that you didn't initialize d
. The preferred C++ way would be to return a vector of the type (you do not need d
anymore)
#include <vector>
....
vector<int> dividers(int y,int x){
int yx;
vector<int> divi;
divi.reserve(100);
if(y > x){
yx = y;
}
if(x > y){
yx = x;
}
for (int n = 1; n <= yx; n++){
if ((n%y==0) && (n%x==0)){
divi.push_back(n);
}
}
return divi;
}
You should read about iterators too to modify the loop that is in your main function.
Big mistake in my code removed... Thanks for pointing it out. I did the same mistake with vector that what you had with the array. Fixed now... Stupid me...
Upvotes: 1