Search code examples
cfunctionpointersvectormultiplication

How to multiply pointer positions in a function?


I am trying to create some functions to handle vector and matrix operations. The vector sum function works as expected, but the dot product function returns always zeros. What I am doing wrong?

Also, I am not sure if this is the best way to handle the problem. I am creating a script for nonlinear optimization. My idea is to allocate memory for the auxiliary scalars, vectors and matrices that are reused on each iteration. The functions are void type to so I can keep track of all variables created in the program.

#include <stdio.h>

void dot (const double *v_1, const double *v_2, double s_out)
{
    s_out = v_1[0] * v_2[0] + v_1[1] * v_2[1];
}

void sum (double *v_1, double *v_2, double *v_out)
{
    v_out[0] = v_1[0] + v_2[0];
    v_out[1] = v_1[1] + v_2[1];
}

int main ()
{
    double *r;
    double *t;
    r = malloc(sizeof(double)*2); 
    t = malloc(sizeof(double)*2); 
    r[0] = 1; r[1] = 2;
    double rho_new = 0;

    dot (r, r, rho_new);
    printf("rho_new = %lf\n", rho_new);
    sum (r, r, t);
    printf("t = %lf %lf\n", t[0], t[1]);
}

Solution

  • Two options to return value from the function.

    #include <stdio.h>
    
    double dot (const double *v_1, const double *v_2)
    {
        return v_1[0] * v_2[0] + v_1[1] * v_2[1];
    }
    
    void sum (double *v_1, double *v_2, double *v_out)
    {
        v_out[0] = v_1[0] + v_2[0];
        v_out[1] = v_1[1] + v_2[1];
    }
    
    int main ()
    {
        double *r;
        double *t;
        r = malloc(sizeof(double)*2); 
        t = malloc(sizeof(double)*2); 
        r[0] = 1; r[1] = 2;
        double rho_new = 0;
    
        rho_new = dot(r, r, rho_new);
        printf("rho_new = %lf\n", rho_new);
        sum (r, r, t);
        printf("t = %lf %lf\n", t[0], t[1]);
    }
    

    #include <stdio.h>
    
    void dot (const double *v_1, const double *v_2, double *s_out)
    {
        *s_out = v_1[0] * v_2[0] + v_1[1] * v_2[1];
    }
    
    void sum (double *v_1, double *v_2, double *v_out)
    {
        v_out[0] = v_1[0] + v_2[0];
        v_out[1] = v_1[1] + v_2[1];
    }
    
    int main ()
    {
        double *r;
        double *t;
        r = malloc(sizeof(double)*2); 
        t = malloc(sizeof(double)*2); 
        r[0] = 1; r[1] = 2;
        double rho_new = 0;
    
        dot (r, r, &rho_new);
        printf("rho_new = %lf\n", rho_new);
        sum (r, r, t);
        printf("t = %lf %lf\n", t[0], t[1]);
    }