returning array from a function

can somebody tell me how to return an array from a function???

hey…
you can simply return the address of first element of an array i.e. at 0th posn …
Can be done by using Pointers…

C++ does not allow to return an entire array as an argument to a function. However, You can return a pointer to an array by specifying the array’s name without an index

eg:
#include

int * fun() 

{ 

	int a[3]={1,2,3}; 
    
	return a;
} 

int main() 

{

int *x; 
    
	x=fun();
	printf("%d",*(x+1));
	return 0;
}
1 Like

What @abhi231594 has done is completely wrong. You should never do that.
Explanation-
Array a in fun() is a local array. It is allocated on stack memory (also called automatic memory), which is reclaimed after function returns. Now he is returning the pointer to that local variable. So what happens?

Undefined behavior.

So you may say it works for you (unfortunately), because for such a small program, no one may modify that particular memory region. But in a large program, it may be modified a dozen times, and your code might end up formatting your hard disk.

The correct ways -

  1. If you want to return pointer to array - you need to allocate memory on heap, using new opperator in C++ or malloc in C. But then it is the responsibility of the caller to deallocate memory using delete operator in C++, free() in C.
  2. The best way however is to pass array as argument, which gets passed by reference. So you can modify the array inside function, and there is no need to return array.
  3. If you are using C++, you can return std::vector, just like any other type. But I haven’t done this so I am not sure.
3 Likes

U can do this . .

struct arr {
   int a[size];
};

struct arr myfun()
{
  struct arr retu;
  //do do and do :P
  return retu;
}

int main()
{
  struct arr ans;
  ans=myfun();
  printf("%d\n",ans.a[0]);
}

Or anytng wrong ?

thanks for correcting me …
i checked it on my compiler .it says
warning: address of local variable `a’ returned
. i m not removing my solution as it could be helpful in explaining your answer to others also… :slight_smile:

@abhi231594: I am glad you have taken it as constructive criticism :slight_smile: We all learn it at some time. Either the hard way, or the soft way! Also it shows that we should pay attention to warnings as well. :smiley:

please add a note that this is not working example as @vinayak garg mentioned

addsome code to be clear what you meant, see also @abhi231594’s answer