new and delete vs vector

C++ beginner here. I am learning dynamic memory allocation recently and trying to compare with vector<> with a small code snippet shown below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include<iostream>
#include<vector>

using namespace std;

struct test{
  vector<double> point_vec; // vector<>
  double* point;            // pointer to vector<>
  double* pointer;          // pointer to a dynamic memory
  test(vector<double> numbers);
  ~test();
};

test::test(vector<double> numbers){

  point_vec = vector<double>(numbers.size()+1, 0);
  for (int i=0; i<numbers.size(); i++){
	point_vec[i+1] = point_vec[i] + numbers[i]; //cumulative sum of numbers
  }
  point = &point_vec[0];
  
  pointer = new double(numbers.size()+1);
  pointer[0] = 0;
  for (int i=0; i<numbers.size(); i++){
	pointer[i+1] = pointer[i] + numbers[i];
	cout << pointer[i+1] << endl;
  }
}

test::~test(){delete[] pointer;}

int test_run(){
  vector<double> numbers(5, 1);
  test test1(numbers);
  for (int i=0; i <numbers.size(); i++){
    cout << test1.point[i] << endl;
  }
  cout << "vec finished." << endl;
  
  for (int i=0; i <numbers.size(); i++){
    cout << test1.pointer[i] << endl;
  }
  cout << "pointer finished." << endl;
  
  return 0;
}

int main(){
  int i = test_run();	
  cout << "i = " << i;
  return 0;
}


The executable on my system (compiled with gcc 4.9.3 on Windows) outputs
1
2
3
4
5
0
1
2
3
4
vec finished.
0
1
2
3
3.875
pointer finished.

So it seems:
1. point_vec/point and pointer are initiated correctly.
2. when test_run prints out point_vec/point just fine, but the 5th element of pointer is wrong
3. program fails for some reason(i=0 not printed at the end).

This piece really confuses me, any help or information will be very much appreciated!
Line 22 creates a single int double that has the initial value of numbers.size()+1.

If you want to create an array you need to use square brackets.

 
pointer = new double[numbers.size()+1];
Last edited on
Thanks Peter! That was a lurking mistake for me :)
Topic archived. No new replies allowed.