Frage

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
War es hilfreich?

Lösung 2

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 ints 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.

Andere Tipps

new int(len) creates a single integer, and initialises it with the value len.

new int[len] creates an array of len integers, uninitialised.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top