What is the problem here in this code?
It gives segmentation fault. I found value of size in vector (int *a)
is no more 3. How is this?
#include <iostream>
using namespace std;
class vector
{
int *v;
int size;
public:
vector(int m)
{
v = new int[size = m];
for(int i=0; i<size; i++)
v[i] = 0;
}
vector (int *a)
{
for(int i=0; i<size; i++)
v[i] = a[i];
}
int operator*(vector &y)
{
int sum = 0;
for(int i=0; i<size; i++)
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(3);
vector v2(3);
v1 = x;
v2 = y;
int R = v1 * v2;
cout << "R = " << R;
return 0;
}
Sincerely,
Srinivas Nayak
In essence the reason it generates a fault is in the line
v1=x;
As you have no assignment operator this in effect becomes:
v1=vector(x)
Which called your int * constructor. This constructor runs with size initialised to garbage which causes the seg fault as the loop progresses towards invalid memory.
Strategically the problem is you want create a new object for a int * but you don’t know how big the array is that you are pointing at.
Your code looks like you want to assume that the array is the correct size for the currently defined vector in which case the operator you want to define this function in preference to the constructor: operator=(int *)
You generally seem a bit confused about which object is which for example
sum += this -> v[i] * y . v[i];
would normally jusy be written as in this context
sum += v[i] * y . v[i];