How do I access the pointer in this struct correct

2019-08-03 03:38发布

问题:

Below are definitions for 2 structs, then a short method body that uses them. I don't understand why the compiler throws the error:

physics.c:95: error: incompatible types in assignment

cpBody and cpSpace are types from an external library, which isn't part of the problem.

typedef struct gameBody gameBody;

struct gameBody
{
    cpBody *body;
    int numberOfShapes;
    cpShape *arrayOfShapes; //This stores an array of pointers to Shapes
};

//Struct that stores the cpSpace object and the array of pointers to the body objects
typedef struct gameSpace gameSpace;

struct gameSpace
{ 
    cpSpace *space;
    int numberOfObjects;
    gameBody *arrayOfObjects;       //This stores an array of gameBodys
};

void physicsAddBody(gameSpace *space, gameBody *body, int objectIndex)
{
    gameBody *array = space -> arrayOfObjects;
    array[objectIndex] = body; //THIS IS WHERE THE ERROR IS THROWN
}

回答1:

array[objectIndex] = body;

On the left side is a gameBody, on the right side a gameBody*.

Do you try to copy the struct or do you want to assign the pointer into a pointer-array?



回答2:

Your last line should be:

array[objectIndex] = *body;

because body is not a gameBody but a pointer to a gameBody.

(and I hope you have allocated the memory somewhere...)