Issue with Vectors

I am trying to initialize a vector with zero and assign values to it(10,20,30 in this example).The program crashes when its executed.
I guess the program crashes when it encounters v[i]=a[i];
Please confirm and kindly help me to understand the problem here.

#include <iostream>
using namespace std;
class vector{
int *v;
public:
vector(int m){
v=new int[m];
for(int i=0;i<=m;i++)
v[i]=0;
}
vector(int *a){
for (int i=0;i<=2;i++){
cout<<a[i];
v[i]=a[i];//Program crashes here ?
}
}
};

int main(){
int x[3]={10,20,30};
vector v1(3);
v1=x;
return 0;
}
This is wrong:
 
for(int i=0;i<=m;i++)

It should be:
 
for(int i=0;i < m;i++)

If you have an array with 3 elements they are numbered 0, 1 and 2.
1
2
3
4
5
int array[3];

array[0] = 0; // first
array[1] = 0; // second
array[2] = 0; // third 
Made the changes, but still the same issue.Please help.
Your second constructor doesn't allocate any memory for the array.
Here:
1
2
3
4
5
6
7
8
int main()
{
	int x[3] =
	{ 10, 20, 30 };
	vector v1(3);
	v1 = x;
	return 0;
}


When you say v1 = x you are trying to add an array to a vector. The types don't match. So the compiler appears to be creating a temporary vector from your array.

So when your constructor runs here:
1
2
3
4
5
6
7
8
9
	vector(int *a)
	{
		for(int i = 0; i <= 2; i++)
		{
			cout << a[i] << endl;
			v[i] = a[i];//Program crashes here ?
		}
	}

it is NOT running on the vector v1, but on a newly created vector.

If a constructor is called it is never being run on an already constructed object. So yours is being called on a new temporary object created by the compiler and it hasn't had any memory allocated to its internal array v because the first constructor has not been run.

Only one constructor is ever run on a given object.
Last edited on
Hi Galik,

Thanks for your prompt response.
Yes, after making the changes to the program as you have mentioned, i am able to assign values to v[i] and perform operations on vectors.

This is the modified code:

#include <iostream>
using namespace std;
class vector{
int *v;
public:
vector(int *a){
v=new int[3];
for(int i=0;i<=2;i++){
v[i]=0;
}
for (int i=0;i<=2;i++){
v[i]=a[i];
}
}
int operator*(vector &y){
int sum=0;
for(int i=0;i<=2;i++){
cout<<this->v[i]<<endl;
sum+=this->v[i]*y.v[i];
}
return sum;
}
};

int main(){
int x[3]={1,2,3};
int y[3]={4,5,6};
vector v1(x);
vector v2(y);
int R=v1*v2;
cout <<"R"<<R<<endl;
return 0;
}

Once again thanks for all your help.
Topic archived. No new replies allowed.