使用C在嵌套结构数组中使用内存分配和数组索引时出错



我是C中编码的新手。我试图在数组中插入值,即x、y和z坐标的初始值。我在我的主要职能范围内工作。这些阵列分别位于结构r和v中,这两个阵列都位于结构vectorsmoon和vectorsearth中。我为数组分配了内存,但在为数组分配值时出现了两个错误。

在结构中选择矢量和坐标时会出现以下错误。

表达式必须具有结构或联合类型

在任何坐标x、y或z中选择第一个索引时出现以下错误。

下标值为gcc

int TimeSteps = 1000;                  /* The amount of timesteps to be evaluated */
struct vec3D
{
double x[TimeSteps];
double y[TimeSteps];
double z[TimeSteps];
};
struct vectors
{
struct vec3D *r;
struct vec3D *v;
};
struct vectors vectorsmoon;
struct vectors vectorsearth;
/*Assigning memory for arrays in structure*/
vectorsmoon.r = (struct Vec3D *)malloc(TimeSteps * sizeof(double));
vectorsmoon.v = (struct Vec3D *)malloc(TimeSteps * sizeof(double));
vectorsearth.r = (struct Vec3D *)malloc(TimeSteps * sizeof(double));
vectorsearth.v = (struct Vec3D *)malloc(TimeSteps * sizeof(double)); 

/* Apply the initial conditions before the calcualtions start */
vectorsearth.r.x[0] = earth.x0;
vectorsearth.r.y[0] = earth.y0;
vectorsearth.r.z[0] = earth.z0;
vectorsearth.v.x[0] = earth.vx0;
vectorsearth.v.y[0] = earth.vy0;
vectorsearth.v.z[0] = earth.vz0;
vectorsmoon.r.x[0] = moon.x0;
vectorsmoon.r.y[0] = moon.y0;
vectorsmoon.r.z[0] = moon.z0;
vectorsmoon.v.x[0] = moon.vx0;
vectorsmoon.v.y[0] = moon.vy0;
vectorsmoon.v.z[0] = moon.vz0;

使用指针时,需要先取消引用指针,然后才能将值存储在分配的内存中。

这里有一个例子:

vectorsearth.r->x[0] = earth.x0;
vectorsearth.r->y[0] = earth.y0;
vectorsearth.r->z[0] = earth.z0;

因为r是指向struct Vec3D的指针,所以需要使用运算符->来访问其成员,而不是常规的点运算符。

最新更新