سؤال

I am trying to implement a fifo cache into a C program. I have a struct:

struct cache{

int blockid;
int used;
char content[SIZE];
};

I made an array of pointers,

struct cache **buffer[size];

And after allocating this cache with the amount of blocks specified, I am having troubles finding the cache entry that stores the block id given (void *get_cache_block(int id) and returning the cached block. I am not sure how to iterate through my array of pointer. Also inserting a new entry into the cache is a function which I am in need of help!

Thanks ahead for the help.

هل كانت مفيدة؟

المحلول

In the code you have shown, you are allocating an array of pointers to pointers, not pointers to structs, the declaration of your cache should be struct cache *buffer[size]. Finding a cache with a given id is a simple for loop, the gist of which is:

int i;
struct cache *cur;

for (i = 0, cur = buffer[0]; i < size; cur = buffer[++i]) {
    if (cur->blockid == id) {
        break;
    }
}

if (i < size) return cur;
else return 0;

The function get_cache_block should return a struct cache * instead of a void * because a void pointer indicates an unknown type.

Additionally, you'll probably want to use a ring buffer for caching, as it has the nice property of overwriting the oldest entry in the buffer when the cache is full. Hopefully that helps and good luck.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top