0

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"

Ivan
  • 5
  • 2

3 Answers3

4

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.

Daniel Goldfarb
  • 6,937
  • 5
  • 29
  • 61
  • 1
    ...or ``, or better even, ``. – DevSolar Oct 14 '20 at 16:38
  • Now I understand, thank you! Do you also know how I can give the velocity, v, an initial value? – Ivan Oct 14 '20 at 16:45
  • Why is it easier to use arrays instead of pointers? – Ivan Oct 14 '20 at 16:46
  • @Ivan v[0] = value. Arrays and pointers are very similar, see https://www.tutorialspoint.com/cplusplus/cpp_pointers_vs_arrays.htm and http://alumni.cs.ucr.edu/~pdiloren/C++_Pointers/neighbor.htm – Ryan Oct 14 '20 at 16:54
  • 1
    @Ivan Re: `Why is it easier to use arrays instead of pointers?` - for once, you won't need to remember deleting what you `new`'ed (you forgot...) – Vlad Feinstein Oct 14 '20 at 16:54
0
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"

0

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>

Vlad Feinstein
  • 10,960
  • 1
  • 12
  • 27