Accessing void * struct
I'm trying to find the bug in my implementation here, where I store a struct in another struct and cannot seem to access the value stored. I define two structs.
typedef struct {
void * data;
} Element;
typedef struct {
void **buckets;
} Storage;
In a separate function, I set key
to be a pointer to a char
. And pass it in to be stored in data.
void Function(const char *key, Storage *storageUnit)
{
char keyValue[strlen(key) + 1];
strcpy(keyValue, key); // To fix the discard qualifiers bit
Element data = { keyValue }; // = new struct element;
printf("Key %s\n", (char *)data.data); // This works.
*(storageUnit->buckets) = &data;
// Let's see if it got st开发者_如何学Pythonored correctly?
Element temp = *(Element *)(storageUnit->buckets);
// This is gobbledygook
printf("Stored correctly with data %s", (char *)(temp.data));
}
What could I be missing?
change
Element temp = *(Element *)(storageUnit->buckets);
to
Element *temp = (Element *)*(storageUnit->buckets);
and print statement from
printf("Stored correctly with data %s", (char *)(temp.data));
to
printf("Stored correctly with data %s", (char *)(temp->data));
EDIT
Not sure if this is a good way to do it, but I am pretty sure you can change
Element temp = *(Element *)(storageUnit->buckets);
to
Element temp = *(Element *)*(storageUnit->buckets);
Without changing the print statement and get the same behavior.
I think maybe you consolidated your posting a bit? at one point it's storageUnit->buckets, then it's cm->buckets. This makes me think the latter printing is actually outside the function, in which case it will blow up because Element data is a local variable that goes away once Function() returns. You've added an automatic to your container.
I think you want Element data = new Element(); data.data = keyValue;
char keyValue[strlen(key)];
is wrong since you use strcpy, you have to account for the nul terminator. make it char keyValue[strlen(key) + 1];
. This is likely what's causing your issue in the last printf.
*(storageUnit->buckets) = &data;
might be wrong too. data
and keyValue
are both allocated on the stack. When your Function
returns, these objects are no longer valid, so storing that pointer in storageUnit->buckets[0] is useless. You should probably allocate the element and the key dynamically with e.g. malloc().
精彩评论