Reputation: 45
This is code for creating vector of size (1,len) for objects:
#include<iostream.h>
class vector
{
int *vect;
int len;
public:
vector(){ vect=NULL; len=0; }
void get_data();
void display();
};
void vector::get_data()
{
cout<<"Enter number of elements: ";
cin>>len;
int *f=new int(len);
vect=f;
cout<<"Enter "<<len<<" values: ";
for(int i=0;i<len;i++) cin>>*(vect+i);
}
void vector::display()
{
for(int i=0;i<len;i++) cout<<*(vect+i)<<" ";
cout<<endl;
}
void main()
{
vector v1,v2;
v1.get_data();
v1.display();
v2.get_data();
v2.display();
v1.display();
}
Output:
Enter number of elements: 5
Enter 5 values: 1 2 3 4 5
1 2 3 4 5
Enter number of elements: 5
Enter 5 values: 6 7 8 9 9
6 7 8 9 9
9 2 3 4 5
Why did the first value of vector object v1 change on creating object v2 ?
When I replaced the line:
int *f=new int(len);
in get_data() to int *f=new int[len];
i got the expected result:
Enter number of elements: 5
Enter 5 values: 1 2 3 4 5
1 2 3 4 5
Enter number of elements: 5
Enter 5 values: 6 7 8 9 9
6 7 8 9 9
1 2 3 4 5
Upvotes: 2
Views: 116
Reputation: 254441
new int(len)
creates a single integer, and initialises it with the value len
.
new int[len]
creates an array of len
integers, uninitialised.
Upvotes: 10
Reputation: 110658
new int(len)
allocates a single int
object and initialises it with the value len
. On the other hand, new int[len]
allocates an array of int
s of length len
.
Compare with int x(5);
and int x[5];
.
When you were allocating only a single int
, cin>>*(vect+i);
was attempting to write to objects that have not been allocated.
Upvotes: 8