0

I'm learning c++ and I'm trying to ask the user to input 4 numbers in a function, and then simply print the array.

int getFourNums();
int main(int argc, char** argv){

    int getNums;

    getNums = getFourNums();

    cout << "The array is: " getNums << endl;
}

int getFourNums(){

    int i;

    int myArray[4];
    cout << "Enter 4 nums: ";
    for(i = 0; i < 4; i++){
        cin >> myArray[i];
    }
    return myArray[i];

As of now, it's letting me get the four numbers, but the result that's printing is "The array is: 0." I'm not quite sure why the array is seemingly not populating.

  • 4
    Your bug is here `return myArray[i];` Your code is attempting to return the single integer that is at `myArray[4]` which is out of bounds. – drescherjm Feb 05 '19 at 21:59
  • you don't print an array, do you? – Stephan Lechner Feb 05 '19 at 22:02
  • Related: https://stackoverflow.com/questions/3473438/return-array-in-a-function – drescherjm Feb 05 '19 at 22:02
  • Also if you wanted to return an array `int getNums;` would not work because this is a single integer not an array. – drescherjm Feb 05 '19 at 22:03
  • The `c++` way to do this is to use `std::array` or `std::vector` although if this is an academic excercise they may want you to do this how you would in `c` – drescherjm Feb 05 '19 at 22:06
  • @StephanLechner I'm just trying to return the array to use in another function, but I was trying to use it in my main function to see if it was populating correctly – user2348258 Feb 05 '19 at 22:07
  • @user2348258 "_I'm just trying to return the array_" Yet, the signature of `int getFourNums()` means, that the function is returning a single `int`. Not an array. – Algirdas Preidžius Feb 05 '19 at 22:08
  • The array is being populated correctly but you are returning myArray[4] since i == 4 at that point. Note that the array does not have an element at that position so it's returning invalid memory and it's return just an int not an array – DavidC Feb 05 '19 at 22:09
  • Arrays can't be assigned, so returning an array never works. Best you can get is a pointer to the array, but since the array a local variable scoped to within `getFourNums`, a pointer to it is useless. The memory is invalid by the time the calling function can do anything with it. Arrays suck. – user4581301 Feb 05 '19 at 22:24

4 Answers4

2

Your fundamental problem is that int getFourNums() can only return a single integer, not an array of them. The next problem is that functions cannot return raw arrays for historical reasons. Your choices are to return a std::array, a struct containing the array, pass the array by reference into the function, or return a std::vector. My preference for this application is a std::vector - it is flexible, and although not quite as efficient as std::array, you should probably default to std::vector unless you have a good reason otherwise. Your getNums code would then look like:

std::vector<int> getFourNums() {
    std::vector<int> result;
    cout << "Enter 4 nums: ";
    for(int i = 0; i < 4; i++){
        int v;
        cin >> v;
        result.push_back(v);
    }
    return result;
}

To print the vector, see this question. My personal preference would be a range-based for loop over the vector; your tastes may vary.

1

One issue in your code is that a loop like

for(i = 0; i < 4; i++){
    cin >> myArray[i];
}

will end up with i==4. Hence, return myArray[i] will exceed array bounds and/or access an uninitialised value then and yield undefined behaviour.

The main issue, however, is that in C++ you'll follow a very different approach and use collection types like std::vector instead of plain arrays. See the following code illustrating this. Hope it helps.

#include <vector>
#include <iostream>

std::vector<int> getFourNums(){

    int val;
    std::vector<int> result;
    cout << "Enter 4 nums: ";
    for(int i = 0; i < 4; i++){
        cin >> val;
        result.push_back(val);
    }
    return result;
}

int main(int argc, char** argv){
    std::vector<int> fourNums = getFourNums();
    for (auto i : fourNums) {
        cout << i << endl;
    }
}
Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58
0

int getFourNums() will only let you return one int, not the whole array and return myArray[i]; is out of bounds since i == 4. You can only use the range [0,3] as indices for your array. Here's a reworked version with comments in the code.

#include <iostream>
#include <vector>

// don't do "using namespace std;" since it includes
// a lot of stuff you don't need.

// Here's a function that will return a vector of int's
// It'll behave much like a C style array
// but can have variable length and you can use
// a lot of standard functions on it.

std::vector<int> getNums(size_t count) {

    // The "array" we'll return with "count" number of
    // default constructed int:s (they will all be 0):

    std::vector<int> myArray(count);

    std::cout << "Enter " << count << " nums: ";

    // A range based for loop that will go through
    // all int:s in "myArray". "num" will be
    // a reference to each int in the vector which
    // means that if you change the value of "num",
    // you'll actually change the value in the vector.

    for(int& num : myArray) {
        // read values into the int currently
        // referenced by num

        std::cin >> num;
    }

    // return the vector by value
    return myArray;
}

// Put main() last so you don't have to forward declare the functions
// it uses

int main() {

    // call getNums with the value 4 to read 4 int:s
    std::vector<int> Nums = getNums(4);

    std::cout << "The array is:";

    // print each int in the vector. There's no need to use
    // a reference to the int:s here since we won't be changing
    // the value in the vector and copying an int is cheap.

    for(int num : Nums) {
        std::cout << " " << num;
    }

    // std::endl is rarely good when you only want to output a newline.
    // It'll flush the buffer with is costly.
    // Make a habit of using "\n" in most cases.

    std::cout << "\n";
}
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
0

I see that you want to return entire array but just look at your return type:

int getFourNums()

You're returning an integer right? In this situation the returned integer is always myArray[4]. Be aware that it's an integer value, you're returning something that doesn't belong to you actually!

So what to do? I suggest you to pass your array to function like this:

 void getFourNums(int myArray[]){
    int i;
    cout << "Enter 4 nums: ";
    for(i = 0; i < SIZE; i++){
        cin >> myArray[i];
    }
}

Now you filled your array. How to print your array then? We can't simply give our array name and tell cout to print it like you did (you couldn't actually!). Nothing magical here. We're going to print your array's element one by one:

void printFourNumbers(int array[])
{
    for(int i = 0 ; i < SIZE ; ++i)
    {
        cout << array[i] << endl;
    }
}

Finally whole code looks like this:

#include <iostream>
using namespace std;
const int SIZE = 4;

void getFourNums(int myArray[]);
void printFourNumbers(int array[]);

int main(int argc, char** argv){
    int myArray[SIZE];
    getFourNums(myArray);
    printFourNumbers(myArray);

}

void getFourNums(int myArray[]){
    int i;
    cout << "Enter 4 nums: ";
    for(i = 0; i < SIZE; i++){
        cin >> myArray[i];
    }
}

void printFourNumbers(int array[])
{
    for(int i = 0 ; i < SIZE ; ++i)
    {
        cout << array[i] << endl;
    }
}
patoglu
  • 401
  • 4
  • 16