0

How to return an Array

Help please , can I return an array from a function ? or only I can pass it to a function ??

18th Nov 2016, 9:51 PM
Bashar
Bashar - avatar
4 Answers
+ 5
just to clarify an array is actually a pointer which point to the address of start of the array, so there is no problem returning it, just as scott demonstrated. also when you pass an array to a function you actually passing it starting adress, so any alterations to it will be valid in the function that called the function which made those alterations. so when you allocate array of integers for example: int * arr = new int[3]; and let's assume that the first adress that was given is 100, and knowing that integer takes 4 bytes, then arr[0] adress is 100 arr[1] adress is 104 arr[2] address is 108 and also don't forget when you allocate memory using the 'new' command, you should not forget to eventually delete it using 'delete' command
18th Nov 2016, 10:47 PM
Burey
Burey - avatar
+ 3
Here is a small example: #include <iostream> using namespace std; int * TestFunc (); int main () { int * NewArray; NewArray = TestFunc (); // Call the test function and assign the address of the returned array into NewArray cout << NewArray[0] << ' ' << NewArray[1] << endl; return 0; } int * TestFunc () { int SomeArray [2] = {5, 6}; return SomeArray; } Keep in mind this does not copy the whole array around, rather it assigns the address.
18th Nov 2016, 10:06 PM
scott johnson
scott johnson - avatar
0
thanks you both , i will try it ;)
18th Nov 2016, 11:30 PM
Bashar
Bashar - avatar
0
Thank you @scott johnson Thank you @Burey It works . There was only stack problem because when I use new pointer it will disappear after exit the function (specially I use separated class file (.h .cpp) ), so i solved that by using heap memory . thanks again
19th Nov 2016, 11:32 AM
Bashar
Bashar - avatar