c - 需要指针帮助

标签 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 是一个结构,包含 xywh< 等字段 所有 int。现在如何访问这些字段?

例如。类似的东西

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

我很困惑

最佳答案

在此:

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
}

关于c - 需要指针帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33327136/

相关文章:

Ms-Dos 的 C99 编译器?

c++ - 如何使用结构来计算引入的男性和女性总数?

c - 如何在 C 中取消引用和自动递增强制转换指针?

c++ - delete[] 触发断点

c - 如何在C中实现string.h的strcmp函数

c - 如何解决这个IP地址错误?

javascript - 将嵌套数组合并为一个?

javascript - 过滤一个 JavaScript 对象数组和另一个 JavaScript 对象数组

构建二叉搜索树时的编译错误

c - 为什么我的 float 被截断了?