classes and pointers

I was expecting that this program will show numbers from 17 to 1. It almost does that, but instead of some values it shows just random garbage numbers (the output is 2293540, 16, 2, 14, 13, 12 ... 4, 4198563, 1 to be exact). What's wrong in this code?
If my code is wrong, how do I declare an array of custom size in the class?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
using namespace std;

class returnarray {
    int n[];
public:
    returnarray(int, int);
    int *returner () {return n;}
};

returnarray::returnarray (int number, int length)
{
    for (int i=0; i<length; i++) {
        n[i] = number;
        number--;
    }
}
int main ()
{
    int length=14;
returnarray object(17, length);
int *p=object.returner();
for (int i=0; i<length; i++) {
    cout << *(p+i) << endl;
}
}
Last edited on
int n[];
An array of undefined length is your problem.
To declare an array of a custom size, you need to dynamically create the array. Here is how I would do it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class ReturnArray {
    public:
        ReturnArray(int value, int length);
        ~ReturnArray();
        int* getArray(void) const { return n; }

    private:
        int* n;
};

ReturnArray::ReturnArray(int value, int length) {
    this->n = new int[length](value);
}

ReturnArray::~ReturnArray() {
    delete[] n;
}

int main() {
    int length = 14;
    ReturnArray object(17, length);
    int* p = object.getArray();
    for (int i = 0; i < length; i++) {
        cout << p[i] << endl;
    }
}
Topic archived. No new replies allowed.