I’m trying to store a string in an array contained within a struct, and access it, but I’m having a hard time. The struct looks like this:
typedef struct {
void **storage;
int numStorage;
} Box;
Box is initialized as such:
b->numStorage = 1000000; // Or set more intelligently
Box *b = malloc(sizeof(Box));
// Create an array of pointers
b->storage = calloc(b->numStorage,sizeof(void *));
In order to set the string, I use this function:
void SetString(Box *b, int offset, const char * key)
{
// This may seem redundant but is necessary
// I know I could do strcpy, but made the following alternate
// this isn't the issue
char * keyValue = malloc(strlen(key) + 1);
memcpy(keyValue, key, strlen(key) + 1);
// Assign keyValue to the offset pointer
b->storage[offset*sizeof(void *)] = &keyValue;
// Check if it works
char ** ptr = b->storage[offset*sizeof(void *)];
// It does
printf("Hashcode %d, data contained %s\n", offset, *ptr);
}
The problem lies when I try to retrieve it again, with the exact same offset:
// Return pointer to string
void *GetString(const Box *b, int offset, const char *key)
char ** ptr = b->storage[offset*sizeof(void *)];
if (ptr != NULL) {
printf("Data should be %s\n", *ptr);
return *ptr;
} else {
return NULL;
}
The returned pointer is gibberish. What could be amiss?
You don’t have to specify the actual memory offset when accessing arrays. Simply give it the index and you will get the correct element.
So, in your third code block:
And in your fourth:
Also, in the second block of code, has
b->numStoragealready been set?