1

抱歉,如果只有我在挠头看这段代码,但有人能解释一下这个链表是如何存储的吗?

特别是我对这个操作感到困惑*((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;
}
4

1 回答 1

1

这段代码执行的操作是:数组“particleBuf”的每个成员都被初始化为数组下一个成员的地址——直到最后一个元素被初始化为空。

这样,每当需要向链表添加新成员时,只需通过读取数组元素来获取下一个要放入的 ParticleBuf,然后更新 headParticle 以指向数组的下一个成员。

于 2012-06-25T01:36:06.567 回答