#include<iostream>
#include<vector>
usingnamespace 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 = newdouble(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!