在指针中需要帮助

时间:2015-10-25 07:06:52

标签: c arrays pointers struct

typedef struct
{
    int mPosX,mPosY;//X & Y coordinates
    int mVelX,mVelY;//Velocity
    SDL_Rect *mColliders;//Dot's Collision Boxes
}dot;

void scale(SDL_Rect* r,size_t capacity)
{
    r=(SDL_Rect*)calloc(capacity,sizeof(SDL_Rect));
}
void rescale(SDL_Rect* r,size_t newcapacity)
{
    r=(SDL_Rect*)realloc(r,sizeof(SDL_Rect)*newcapacity);
}
void gc(SDL_Rect* r)
{
    free(r);
    r=NULL;
}


void dot_init(dot *d,int x,int y)
{
    //Initialize the Offsets
    d->mPosX=x;
    d->mPosY=y;
    scale(d->mColliders,11);
    //Initialize the velocity
    d->mVelX=0;
    d->mVelY=0;

SDL_Rectis a结构并包含xywh等字段 所有int。现在如何访问这些字段?

实施例。喜欢的东西

d->mColliders[2].h=1;
d->mColliders[3].w=16;//This ain't working

我很困惑

1 个答案:

答案 0 :(得分:1)

在此:

void scale(SDL_Rect* r,size_t capacity)
{
    r=(SDL_Rect*)calloc(capacity,sizeof(SDL_Rect));
}

void dot_init(dot *d,int x,int y)
{
    //Initialize the Offsets
    d->mPosX=x;
    d->mPosY=y;

    d->mColliders = NULL;
    scale(d->mColliders,11);
    // here d->mColliders is still NULL
}

在调用scale之后,d->mColliders仍为NULL,因为指针传递给函数的方式使得它只能在本地修改。

查看并运行一个说明此内容的最小示例:https://ideone.com/rIjoOC

你应该写(需要C ++):

void scale(SDL_Rect*& r,size_t capacity) // not the reference to pointer with &
{
    r=(SDL_Rect*)calloc(capacity,sizeof(SDL_Rect));
}

void dot_init(dot *d,int x,int y)
{
    //Initialize the Offsets
    d->mPosX=x;
    d->mPosY=y;

    d->mColliders = NULL;
    scale(d->mColliders,11);
    // here d->mColliders is not NULL
}

在C中,使用双指针而不是引用,然后执行:

void scale(SDL_Rect** r,size_t capacity)
{
    *r=(SDL_Rect*)calloc(capacity,sizeof(SDL_Rect));
}

void dot_init(dot *d,int x,int y)
{
    //Initialize the Offsets
    d->mPosX=x;
    d->mPosY=y;

    d->mColliders = NULL;
    scale(&(d->mColliders),11);
    // here d->mColliders is not NULL
}

或(适用于C和C ++):

SDL_Rect* scale(size_t capacity) // simply return the allocated array
{
    return (SDL_Rect*)calloc(capacity,sizeof(SDL_Rect));
}

void dot_init(dot *d,int x,int y)
{
    //Initialize the Offsets
    d->mPosX=x;
    d->mPosY=y;

    d->mColliders = NULL;
    d->mColliders = scale(11);
    // here d->mColliders is not NULL
}