-1

I want to read from user input some numbers and then display them 5 on each line. My code is like this:

#include <iostream>
using namespace std;

const int INPUT_SIZE = 7;

void printValues(int *b) {

    int counter = 0;
    while (counter < INPUT_SIZE) {
        cout << *(b+counter) << " ";
        if ((counter + 1) % 5 == 0 && counter>0) {
            cout << endl;
        }

        counter++;
    }
    cout << endl;
    system("pause");
}

int * readValues() {
    int b[INPUT_SIZE];
    for (int i = 0; i < INPUT_SIZE; i++) {
        cout << "Enter element on position: " << i << ": ";
        cin >> b[i];
    }
    return b;
}

int main() {

    int* b;
    b = readValues();
    printValues(b);

    return 0;
}

However, when I try to print them, I get some weird numbers which I think are memory locations. How do I print an array and also how do I write a function that returns an array? I have little experience with pointers, as I only coded in Java so far. Help much appreciated.

1 Answers1

2

Your array, b, is a local variable inside the function readValues.

When readValues exits, the array is destroyed.

The pointer which you return from readValues is invalidated as soon as the function returns. Trying to use it (e.g. by passing it to printValues) is incorrect (formally, it causes undefined behaviour).

You may have caused some confusion by giving the same name b to a pointer variable in main as you do to the array b in readValues. They are entirely separate variables.

If you want to use the same array in your two functions, you need to make sure it lives in a scope which ensures it lives as long as you need it to. This could be by making it a local variable in main.

CB Bailey
  • 700,257
  • 99
  • 619
  • 646