在C中使用自定义向量

时间:2016-07-06 14:20:00

标签: c vector

我是C / C ++的新手,但我正在尝试调试一些代码。它使用了一个有人称之为CART8的向量,其结构如下:

typedef struct crt8 {
    double x;
    double y;
    double z; } CART8;

现在我的问题是这个。如何创建和填充名为vector1的CART8类型向量的实例?我已经阅读了很多材料,甚至找到了一个指示如何创建矢量的网站......如上所示,但没有关于如何实际使用它的信息。

3 个答案:

答案 0 :(得分:3)

typedef在C中广泛用于引用struct变量而不指定struct前缀,例如,如果我有:

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

而不是初始化它我必须这样做:

struct vector vector1;
vector1.x = 1.11;
vector1.y = 1.22;
vector1.z = 1.33;

但是如果我在声明中使用typedef

typedef struct vector {
        double x;
        double y;
        double z;
    } vector_type;

比我可以简化这样的初始化(注意现在不需要结构前缀):

vector_type vector1;
vector1.x = 1.11;
vector1.y = 1.22;
vector1.z = 1.33;

当然,在这种情况下,我仍然可以使用完整的struct vector初始化

所以在你的情况下:

#include <stdio.h>

typedef struct crt8 {
    double x;
    double y;
    double z;
} CART8;

int main(int argc, char** argv)
{
    CART8 vector1;
    vector1.x = 2.526;
    vector1.y = 3.416;
    vector1.z = 4.32;
    printf("%f %f %f\n", vector1.x, vector1.y, vector1.z);
}

或者,您始终可以使用原始结构定义:

#include <stdio.h>

typedef struct crt8 {
    double x;
    double y;
    double z;
} CART8;

int main(int argc, char** argv)
{

    struct crt8 x;
    x.x = 2.341;
    x.y = 3.43;
    x.z = 4.521;
    printf("%f %f %f\n", x.x, x.y, x.z);
}

答案 1 :(得分:3)

您写道:

typedef struct crt8 {
    double x;
    double y;
    double z;
} CART8;

这定义了一个新的'类型'。 'typename'是struct crt8或您定义的别名CART8。这是在C:

中实例化该类型的对象的方法
    struct crt8 myVector;

或者你可以使用你定义的别名'CART8':

    CART8 myVector;

无论哪种方式,这都是你填充对象'成员'的方式:

    CART8 x; // Creation of object
    x.x = 100;
    x.y = 101;
    x.z = 102;

答案 2 :(得分:2)

这是一个演示程序,它显示了如何创建,初始化和使用结构对象的各种方法。

#include <stdio.h>
#include <math.h>

typedef struct crt8 {
    double x;
    double y;
    double z; } CART8;

int main( void ) 
{
    CART8 vector1 = { 1.1, 2.2, 3.3 };

    CART8 vector2 = { .x = 1.1, .y = 2.2, .z = 3.3 };

    CART8 vector3;
    vector3.x = 1.1;
    vector3.y = 2.2;
    vector3.z = 3.3;

    CART8 vector4 = vector1;

    CART8 vector5 = { vector1.x + vector2.z, vector1.y + vector2.y, vector1.z + vector2.x };

    printf( "vector5 = { %lf, %lf, %lf }\n", vector5.x, vector5.y, vector5.z );

    printf( "Magnitude = %lf", sqrt( pow( vector1.x, 2 ) + pow( vector1.y, 2 ) + pow( vector1.z, 2 ) ) );

    return 0;
}

输出

vector5 = { 4.400000, 4.400000, 4.400000 }
Magnitude = 4.115823