Sorry if its just me who is scratching the head looking at this code, but could someone explain how is this linked list stored?
In particular I am puzzled by this operation *((Particle**)p) = (p++)+1; – how to interpret operation on the left side pointer?
#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;
}
The operation being done by that piece of code is: Every member of the array ‘particleBuf’ is initialized to the address of the next member of the array – until the last element, which is initialized to null.
This way, whenever you need to add a new member to the link list, you can just obtain the next ParticleBuf to put it into by reading an array element, and then updating the headParticle to point to the next member of the array.