I can't seem to get pointer conversions right, I've made a small Stash struct to hold things in bytes, but when I tried to output anything from the Stash it becomes NULL. Heres the code for the Stash.
Code:
typedef struct StashTag {
size_t size; /* Size of each space */
int quantity; /* Number of avaliable spaces */
int items; /* Number of items currently held */
byte* storage; /* Array of bytes */
} Stash;
/* Initialise and cleanup */
void initialise(Stash* s, size_t data_size) {
s->size = data_size;
s->quantity = 0;
s->items = 0;
s->storage = NULL;
return;
}
void clean(Stash* s) {
if(s->storage != NULL) {
free(s->storage);
}
s->size = 0;
s->quantity = 0;
s->items = 0;
s->storage = NULL;
return;
}
/* Memory routines */
int inflate(Stash* s, int increase) {
if(increase > 0) {
int new_quantity = s->quantity+increase;
int new_bytes = new_quantity*s->size;
int old_bytes = s->quantity*s->size;
int j;
byte* new_storage = (byte*)malloc(new_quantity);
if(s->storage != NULL) {
for(j = 0; j < old_bytes; ++j) {
new_storage[j] = s->storage[j];
}
free(s->storage);
}
s->storage = new_storage;
s->quantity = new_quantity;
return(1);
}
else {
return(0);
}
}
/* Stash operations */
int put(Stash* s, const void* item) {
if(sizeof((byte*)item) == s->size && s->items < s->quantity) {
int start_location = s->items*s->size;
int final_location = (s->items+1)*s->size;
int j, k;
byte* temp = (byte*)item;
for(j = start_location, k = 0; j < final_location; ++j, ++k) {
s->storage[j] = temp[k];
}
++(s->items);
return(s->items);
}
else {
return(0);
}
}
void* get(Stash* s, int item_number) {
if(item_number > 0) {
byte* segment = (byte*)malloc(s->size);
int j, k;
int start_location = (item_number-1)*s->size;
int final_location = item_number*s->size;
for(j = 0, k = start_location; k < final_location; ++j, ++k) {
segment[j] = s->storage[k];
}
return((void*)segment);
}
else {
return((void*)0);
}
}
And this is the test-run.
Code:
int main() {
Stash intStash;
int i, j;
initialise(&intStash, sizeof(int));
inflate(&intStash, 100);
for(i = 1; i < 15; ++i) {
if(put(&intStash, &i)) {
printf("done!");
}
}
j = *((int*)get(&intStash, 15));
printf("j is |%d|", j);
printf("\n");
system("PAUSE");
return 0;
}
But it outputs "j is |0|", help!