>>I just can't get it working.
It's tricky when you want to put different sized data at random places in a block of memory that doesn't distinguish between them :-) I would do it with a flag before every subblock telling the type so that you can read the right values
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
enum {BIT8 = -1, BIT32 = -2};
static signed char *mem_block;
static size_t index;
static void seek_begin(void)
{
index = 0;
}
static void set_block(signed char type, int data)
{
size_t size = (type == BIT8) ? sizeof(signed char) : sizeof(int);
mem_block[index++] = type;
memcpy(mem_block + index, &data, size);
index += size;
}
static int get_block(void)
{
size_t size;
int buffer = 0;
size = (mem_block[index++] == BIT8) ? sizeof(signed char) : sizeof(int);
memcpy(&buffer, &mem_block[index], size);
index += size;
return buffer;
}
int main(void)
{
mem_block = malloc(1024);
set_block(BIT8, 127);
set_block(BIT32, 5000);
seek_begin();
printf("Recovered -- %d\n", get_block());
printf("Recovered -- %d\n", get_block());
free(mem_block);
return 0;
}
The above code doesn't worry about errors by the way, you'd have to add such checking :-)