lundi 28 septembre 2020

How can I alter an array from inside a function in C++

I am trying to write a c++ rk4 algorithm and I seem to be running into the same error no matter what I try. I can compile the program but I keep getting a zsh: segmentation fault (core dumped) ./main. I believe that the problem is within the rk4 function here:

void funcs::rk4(double *p_vec, double h)
{

    double *k0, *k1, *k2, *k3, *l0, *l1, *l2;


    k0 = force( p_vec );

    for ( int inst = 0; inst < 2; ++inst )
    {
        l0[ inst ] = p_vec[ inst ] + h*( k0[ inst ] );
    }

    k1 = force( l0 );

    for ( int inst = 0; inst < 2; ++inst )
    {
        l1[ inst ] = p_vec[ inst ] + ( h/2 ) * ( k1[ inst ] );
    }

    k2 = force( l1 );

    for ( int inst = 0; inst < 2; ++inst )
    {
        l2[ inst ] = p_vec[ inst ] + ( h/2 ) * ( k2[ inst ] );
    }

    k3 = force( l2 );

    for ( int inst = 0; inst < 2; ++inst )
    {
        ( p_vec )[ inst ] += ( ( k0[ inst ] ) + 2*( k1[ inst ] ) + 2* ( k2[ inst ] ) + ( k3[ inst ] ) )*( h/6 );

    }

}

Here is the main function as well if that helps:

#include <iostream>
#include <fstream>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include "functions.h"

using namespace std;

int main( int argc, char **argv )
{
    float alpha = 0, beta = 1;
    int Number = 1000;
    double h = ( beta - alpha )/ Number;
    double postiton_0 = 1.0, velocity_0 = 0.0;

    vector<double> time = funcs::linspace( alpha, beta, Number );
    double p_vector[2] = { postiton_0, velocity_0 };

    for ( int inst = 0; inst <= Number; ++inst )
    {
        funcs::rk4( p_vector, h );

        cout << inst << ", " << p_vector[ 0 ]
            << ", " << p_vector[ 1 ] << endl;
    }

    return 0;

}

Thank you very much in advance!

Aucun commentaire:

Enregistrer un commentaire