Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.6k views
in Technique[技术] by (71.8m points)

c - 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
", rho_new);
    sum (r, r, t);
    printf("t = %lf %lf
", t[0], t[1]);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
", rho_new);
    sum (r, r, t);
    printf("t = %lf %lf
", 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
", rho_new);
    sum (r, r, t);
    printf("t = %lf %lf
", t[0], t[1]);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...