Rick Jansen
Rick Jansen

Reputation: 31

Error using memory allocation and array indexing in nested structure array using C

I am new to coding in C. I am trying to insert values inside an array, the initial values of the x,y and z coordinate. I am working inside my main function. These arrays are in a structure r and v respectively, which both are in structure vectorsmoon and vectorsearth. I assigned memory for the arrays, but I am getting two errors when assigning a value to an array.

The following error arises at selecting a vector and coordinate in the structure.

expression must have struct or union type

The following error arises at selecting the 1st index in any coordinate x, y or z.

subscripted value is 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;



Upvotes: 0

Views: 34

Answers (1)

Lev M.
Lev M.

Reputation: 6279

When you use a pointer, you need to de-reference it before you can store a value in the allocated memory.

Here is an example:

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

Because r is a pointer to struct Vec3D you need to use the operator -> to access its members instead of the regular dot operator.

Upvotes: 2

Related Questions