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

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. Commented Sep 17, 2022 at 19:45
  • 4
    "How to return an array..." - Use either std::array or std::vector . Commented Sep 17, 2022 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. Commented Sep 17, 2022 at 19:48

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Your reasonable answer has the Check mark. I'm pretty sure OP is still struggling.
arr is a somewhat misleading name for a std::vector.
Also, if you reserve a size for your vector when you create it, you can read directly into it's elements. std::vector<int> vec(a); for (auto &i : vec) { std::cin >> i; }

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.