1

I try to return an array from function in C++. I made a very easy function to demonstrate it.

#include<iostream>
using namespace std;

int OneDimensional();

void main()
{
    int arr[3];
    arr = OneDimensional();

    cout<<"arr = " << arr[0] <<endl;

    cin.get(); cin.get();
}

int OneDimensional()
{
    int arr[3];
    cout << "Enter a number" <<endl;
    cin  >> arr[0];
    cout << "Enter a number" <<endl;
    cin  >> arr[1];
    cout << "Enter a number" <<endl;
    cin  >> arr[2]; 
    return arr;
}

But it fails with a lot of errors.

Black
  • 12,789
  • 26
  • 116
  • 196
  • for further reading: [What should main() return in C and C++?](http://stackoverflow.com/q/204476/3953764) – Piotr Skotnicki Sep 24 '15 at 07:23
  • arr in OneDimensional allocates array on its stack and you are trying to return pointer to stack - very bad idea. Also a lot of bugs. Try read some book on C/C++ programming. – Nikolai Sep 24 '15 at 07:27
  • There are no bugs tho, other than the not working function – Black Sep 24 '15 at 08:03

2 Answers2

0

you need to use a pointer.

int * OneDimensional()
{
    static int arr[3];
    cout << "Enter a number" <<endl;
    cin  >> arr[0];
    cout << "Enter a number" <<endl;
    cin  >> arr[1];
    cout << "Enter a number" <<endl;
    cin  >> arr[2]; 
    return arr;
}

void main()
{
    int *arr;
    arr = OneDimensional();

    for (int i = 0; i < length; i++ )// length is number of elements in array
   {
       cout<<"arr = "<< *(arr + i) << endl;
   }
}

Check the example here

Himanshu
  • 4,224
  • 16
  • 28
  • 36
-2
  • int OneDimensional() return only a int value, not an array.
  • main() doesn't have a return

You need read more about C or C++.

Goold Luck!

David Isla
  • 623
  • 7
  • 18