how do we return an array of n elements?
Return an array of n elements
Hii Nikhil
Let me take an example to explain it:
//notice pointer before function name,that is basically suggesting return type(array)
int *arr()
{
/This is important—> remember not to do it like int arr[2], if you do that you will get unexpected result, so while returning an array from function do remember to initialize it dynamically…Dynamically allocated memory remains there until we delete it using delete/
int *arr=new int[2];
arr[0]=1;
arr[1]=2;
//returning array
return arr;
}
int main()
{
//assigning value of array returned by above function to our input array
int *input=arr();
for(int i=0;i<2;i++)
cout<<input[i]<<endl;
return 0;
}
Output will be:
1
2
I hope I was clear…Let me know for any further doubts! Or mark the doubt as resolved if you are clear with it…!
here…in ur example…you have intialised the array element by element…t
Yes Nikhil
You can do it in for loop as well
int *array=new int[2];
for(int i=0;i<2;i++)
array[i]=i+1;
Is that what you are asking?
when we pass the array in a function,then modify its contents,and then return it,we do not face any problem,but in this case also,the the stack has been disolved so why don’t we face any problem here?
Nikhil
First, dynamically allocated array takes memory from heap section not stack.
Now, it will only be deallocated if you delete it via delete() method!
This is what you are asking?
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.