Segmentation fault

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • prasoonthegreat
    New Member
    • Mar 2009
    • 1

    Segmentation fault

    Look at the following code....


    Code:
    #include<iostream>
    using std::cout;
    using std::endl;
    
    const int size=3;
    
    template<class T>
    class vector
    {
        T *v;
    
        public:
    
        vector()
        {
            v=new T[size];
    	    for(int i=0;i<size;i++)
               v[i]=0;
           cout<<"Hello 1";
    	}
    
        vector(T *a)
        {
    		//v=new T[size];
            for(int i=0;i<size;i++)
    	       v[i]=a[i];
        
    	cout<<"Hello";
    	}
    
    	/*void operator=(const T *a)
    	{
           for(int i=0;i<size;i++)
    	       v[i]=a[i];
        }*/
    
        T operator*(const vector &y)
        {
            T prod=0;
    
            for(int i=0;i<size;i++)
               prod += this->v[i] * y.v[i];
    
            return prod;
        }
    };
    
    int main()
    {
         int x[3]={1,2,3};
         int y[3]={4,5,6};
    
         float a[3]={1.7,2.3,3.2};
         float b[3]={1.9,2.4,3.8};
    
         
    
         vector <int> v1;
         vector <int> v2;
    
         vector <float> v3;
         vector <float> v4;
    
         v1=x;
         v2=y;
    
         v3=a;
         v4=b;
    	 
         int Prod_Int = v1 * v2;
    
         float Prod_Float = v3 * v4;
    
         cout<<"Prod_Int = "<<Prod_Int<<endl;
         cout<<"Prod_Float = "<<Prod_Float<<endl;
    
    
         return 0;
    }
    In the above code....althoug h memory has been allocated to object v1 in the default constructor ......why do we need to allocate it again in the parametrized constructor???? ...otherwise i am getting a seg fault
    Last edited by acoder; Mar 24 '09, 10:07 PM. Reason: Added [code] tags and moved to C/C++ forum
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Originally posted by prasoonthegreat
    In the above code....althoug h memory has been allocated to object v1 in the default constructor ......why do we need to allocate it again in the parametrized constructor???? ...otherwise i am getting a seg fault
    What happens in function f() doesn't automagically happen in function g() even if both f() and g() happen to be constructors.

    btw. your thread belongs in the C/C++ topics forum (the 'answers' section). I'm sure some kind soul move it there.

    kind regards,

    Jos

    Comment

    Working...