0

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?

3 Answers 3

2

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:

b->storage[offset] = keyValue;

And in your fourth:

char *ptr = b->storage[offset];
if (ptr != NULL) {
    printf("Data should be %s\n", ptr);
    return ptr;
} else {
 return NULL;
}

Also, in the second block of code, has b->numStorage already been set?

Sign up to request clarification or add additional context in comments.

Comments

2
b->storage[offset*sizeof(void *)] = &keyValue;

This stores the address of the local variable keyValue in the array. Once the function completes, this address becomes invalid. I think you want:

b->storage[offset*sizeof(void *)] = keyValue;

and then make the corresponding change while retrieving.

Comments

2

Doesn't this:

b->storage[offset*sizeof(void *)] = &keyValue

set storage[offset*sizeof(void*)] to point to the address of the local variable keyValue? i.e. no longer valid after function returns

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.