简体   繁体   中英

how to copy Int array to int pointer using constructor in C++

I am trying to insert int array x to int *v. here is my code . please provide me with optimal solutions and the reason behind it.

there is an error in this line. Instead of copying array value its taking garbage value. line v1=x;

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 += v[i] * y.v[i];
        return sum;
    }
    void disp()
    {
        for (int i = 0; i < size; i++)
            cout << v[i] << " ";
        cout << "\n";

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

You forgot to add the assignment operator in your vector class:

  vector & operator=(int *a)
  {
    for (int i = 0; i < size; i++)
      v[i] = a[i];

    return *this;
  }

In the the line

v1=x;

May be, you are expecting it to invoke the second constructor which takes int* as argument. But it won't happen.

It can be seen as Type Conversion from Basic type to Class type . where we expect appropriate constructor will get invoked.
see http://www.hexainclude.com/basic-to-class-type-conversion/

But remember, Constructor will be invoked only once after the creation of object.

Here, in the line

vector v1(3);

the first constructor was already invoked. Then the line

v1=x;

won't invoke the second constructor now.

For every class, = operator is default overloaded . That is the reason why we can easily assign objects to one another.

Therefore, the line v1=x invokes default overloaded assignment = operator. Here, it treats address of array x ie, &x[0] as address of class object. As it is not address of vector class object

=> it results a Segmentation fault .

YOUR ANSWER

To assign int array to int pointer ie, to the member variable int* v of the vector class ,

  1. overload assignment operator = inside the class .

or

  1. Initialize the class object to array in first line itself. ie,

vector v1=x; // modify the class constructor to have size as a constant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM