在C中制作标量乘法函数

时间:2015-10-20 04:11:16

标签: c vector scalar

我编写了一个函数定义来获取向量的标量乘法。我得到了一个可以使用的原型,但是在理解指针时却感到困惑。这是原型。

void scalar_mult(double k, const threeVec_t *src, threeVec_t *dest);
// REQUIRES: src and dest point to threeVec_t objects.
// PROMISES: *dest contains the result of scalar multiplication
//   of k and *src.

struct threeVec {
  double x;
  double y;
  double z;
};

typedef struct threeVec threeVec_t;

这是我的代码,我做错了什么?

void scalar_mult(double k, const threeVec_t *src, threeVec_t *dest)
{
    int i, j, result;
    for (i = 0; i < src; i++) {
                for (j = 0; j < dest; j++) {
                        result[i][j] = k * result[i][j];
}

1 个答案:

答案 0 :(得分:0)

您将result声明为

int i, j, result;

但是你将result视为2D数组是错误的。

你在找这样的东西吗?

// it is the callers duty whether the src is null or not
void scalar_mult(double k, const threeVec_t *src, threeVec_t *dest)
{
    dest->x = src->x * k;// arrow operator as member accessed by pointer 
    dest->y = src->y * k;
    dest->z = src->z * k;
}

您可以这样从scalar_mult致电main

int main() {
    threeVec_t src = {2.0, 3.0, -1.0};
    threeVec_t dest;
    double k = 3.0;

    scalar_mult(k, &src, &dest);

    printf("x = %lf, y = %lf, z = %lf", dest.x, dest.y, dest.z); // Dot operator as member accessed by object 
    return 0;
}

Click here to run live