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
是一个结构,包含 x
、y
、w
、h< 等字段
所有 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/