Allocating Dynamic Array as Data Member

I'm new to dynamic arrays and am not totally clear on how to implement them correctly. I'm making a program that creates and displays n-dimensional vectors. This is what I've written but it causes my program to crash. The program works fine if I display one vector object but not two. So the problem must be in my constructor. Anyone see what I did wrong?

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <iostream>
using namespace std;

class Vector
{
    private:
        float *component;
        int dimension;
    public:
        Vector(float*, int);
    friend ostream &operator<<(ostream&, const Vector&);
};

Vector::Vector(float *newVector, int newDimension)
{
    component=new float(dimension);
    dimension=newDimension;

    int cnt;
    for(cnt=0;cnt<dimension;cnt++)
    component[cnt]=newVector[cnt];
}

ostream &operator<<(ostream &out, const Vector &vec)
{
    int cnt;
    out<<"(";
    for(cnt=0;cnt<vec.dimension;cnt++)
    {
        out<<vec.component[cnt];
        if(cnt<vec.dimension-1)
        out<<", ";
    }
    out<<")";
    return out;
}

int main()
{
   float ar1[] = {1, 2, 3};
   Vector v1(ar1, 3);

   float ar2[] = {1, 2, 3, 4};
   Vector v2(ar2, 4);

   cout << "v1: " << v1 << endl;
   cout << "v2: " << v2 << endl;

   system("pause");
   return 0;
}


The output should be:
v1: (1, 2, 3)
v2: (1, 2, 3, 4)

But it crashes after displaying the first parentheses of v1. I'm pretty sure the problem isn't my ostream function because it works in other programs.
shouldn't line 16 be:
 
    component=new float[dimension];

Also, put line 17 before line 16.
dimension is used before it is defined.
Last edited on
Topic archived. No new replies allowed.