抱歉,如果只有我在看这段代码而挠头,但有人能解释一下这个链表是如何存储的吗?
特别是我对这个操作感到困惑 *((Particle**)p) = (p++)+1;
- 如何解释左侧指针上的操作?
#include <stdio.h>
typedef struct Particle_s {
int myint;
char test_string[10];
} Particle;
#define maxParticles 10
static Particle particleBuf[maxParticles]; // global static array
static Particle* headParticle;
void initParticleAllocator()
{
Particle* p = particleBuf;
Particle* pEnd = particleBuf+maxParticles-1;
// create a linked list of unallocated Particles
while (p!=pEnd)
*((Particle**)p) = (p++)+1;
*((Particle**)p) = NULL; // terminate the end of the list
headParticle = particleBuf; // point 'head' at the 1st unalloc'ed one
}
Particle* ParticleAlloc()
{
// grab the next unalloc'ed Particle from the list
Particle* ret = headParticle;
if (ret)
headParticle = *(Particle**)ret;
return ret; // will return NULL if no more available
}
void ParticleFree(Particle* p)
{
// return p to the list of unalloc'ed Particles
*((Particle**)p) = headParticle;
headParticle = p;
}
int main(int argc, char **argv)
{
int i;
initParticleAllocator();
for( i=0; i<maxParticles; i++) {
Particle* newparticle = ParticleAlloc();
printf("test cell %d (0x%x - 0x%x)\n", i, &particleBuf[i], newparticle);
}
getc(stdin);
return 0;
}
最佳答案
这段代码完成的操作是:数组“particleBuf”的每个成员都被初始化为数组下一个成员的地址 - 直到最后一个元素被初始化为 null。
这样,每当需要向链表添加新成员时,只需通过读取数组元素获取下一个要放入的 ParticleBuf,然后更新 headParticle 以指向数组的下一个成员.
关于c - 数组上的链表分配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11182573/