c - 数组上的链表分配器

标签 c pointers

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

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

相关文章:

c - mc56f8367头文件的要求

c - C中数组指针的奇怪行为

c - "for-Loop"增量的特定顺序

c++ - 在 C++ (Vulkan) 中处理 C 代码

c - 如何在结构中的字符串上实现 fnv1a 哈希函数?

C: 复制一个 char *指针到另一个

c - 2 结构在 C 中使用 1 个指针

c++ - 应该如何设计两个紧密相关的数据结构的所有权?

c - 在 C 中删除另一个字符串中出现的字符串(代码和错误消息)

c - Wireless.h 如何打印出信号电平?