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' のすべてのメンバーは、配列の次のメンバーのアドレスに初期化されます。最後の要素までは、null に初期化されます。

このように、新しいメンバーをリンク リストに追加する必要があるときはいつでも、配列要素を読み取り、配列の次のメンバーを指すように headParticle を更新することで、次の ParticleBuf を取得して配置できます。

于 2012-06-25T01:36:06.567 に答える