Reputation: 25
I just started using c ++. I am trying to run a forward Euler, where I use a for loop and pointers. But I don't understand what's wrong?
#include <iostream>
using namespace std;
void euler(){
int n = 10;
double dt = 0.1;
double *a=new double[n];
double *v=new double[n];
double *t = new double[n];
int vr = 5;
for (int i=0;i<n; i++){
a[i+1] = vr + i;
v[i+1] = v[i] + a[i+1]*dt;
t[i+1] = t[i] + dt;
}
cout << v << endl;
}
int main(int argc, char const *argv[]) {
euler();
return 0;
}
The terminal gives me this "0x7fce7cc017d0"
Upvotes: 0
Views: 244
Reputation: 11311
You can make your original code print the content of vector v
if you implement operator <<
for vecotor
, for example like here:
Overloading output stream operator for vector<T>
Upvotes: 0
Reputation:
double *v=new double[n];
...
cout << v << endl;
V is a pointer to an array of n doubles.
When you are printing you are printing the value of the pointer.
Which is why you get results like "0x7fce7cc017d0" because that's the value of the pointer.
If you want to print out the values of the array you must index into it properly.
std::cout << v[0] << "\n"
Upvotes: 0
Reputation: 7714
You are printing out the pointer itself, instead of the value to which it is pointing. Try one of these:
cout << *v << endl;
or
for (int i=0;i<n; i++)
cout << v[i] << endl;
Also, as mentioned in a commment, no need for the +1
in your array indexing. By the way, this is not a good use of pointers in C++. In general, you don't want to use pointers unless you really need to. With code as simple as yours, you can simply declare arrays.
Upvotes: 4