0

This is my code

*int my_arr(int a) {
    int arr[a];
    for (int i = 0; i < a; i++) {
        cin >> arr[i];
    }
    return arr;
}

I keep getting errors

Chris
  • 26,361
  • 5
  • 21
  • 42
Robert
  • 83
  • 3
  • 4
    It's impossible to return an array from a function in C++. It's also not legal to declare an array with a variable size in C++. Life is much easier if you use a `std::vector` instead. Both of those things are legal for vectors. – john Sep 17 '22 at 19:45
  • 4
    "_How to return an array..."_ - Use either [`std::array`](https://en.cppreference.com/w/cpp/container/array) or [`std::vector`](https://en.cppreference.com/w/cpp/container/vector) . – Richard Critten Sep 17 '22 at 19:46
  • If you changed `*int` to `int*` your code would (perhaps) compile, but it would still be bugged, and you are still not returning an array, you would be returning a pointer. And that pointer would be pointing at an array which no longer existed. – john Sep 17 '22 at 19:48

1 Answers1

3

You can't return an array in cpp. Instead use vectors.

vector<int> my_arr(int a) {
    vector<int> arr;
    for (int i = 0; i < a; i++) {
        int input;
        cin >> input;
        arr.push_back(input);  // to push elements into vector
    }
    return arr;
}
Chris
  • 26,361
  • 5
  • 21
  • 42
Aniket Sinha
  • 235
  • 8
  • Your reasonable answer has the Check mark. I'm pretty sure OP is still struggling. – Captain Giraffe Sep 17 '22 at 20:03
  • `arr` is a somewhat misleading name for a `std::vector`. – Chris Sep 17 '22 at 20:14
  • 1
    Also, if you reserve `a` size for your vector when you create it, you can read directly into it's elements. `std::vector vec(a); for (auto &i : vec) { std::cin >> i; }` – Chris Sep 17 '22 at 20:19