如何正确访问此结构中的指针?

时间:2013-02-17 08:30:34

标签: c pointers struct

下面是2个结构的定义,然后是使用它们的简短方法体。 我不明白为什么编译器会抛出错误:

  

physics.c:95:错误:赋值中不兼容的类型

cpBodycpSpace是来自外部库的类型,这不是问题的一部分。

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
}

2 个答案:

答案 0 :(得分:2)

  

array [objectIndex] = body;

左侧是gameBody,右侧是gameBody*

您是否尝试复制结构,或者是否要将指针指定为指针数组?

答案 1 :(得分:0)

你的最后一行应该是:

array[objectIndex] = *body;

因为body不是gameBody而是指向gameBody的指针。

(我希望你已经在某个地方分配了内存......)