我试图在一个包含在一个结构中的数组中存储一个字符串,并访问它,但我很难。该结构是这样的:分配和访问结构中指向字符串的指针
typedef struct {
void **storage;
int numStorage;
} Box;
盒被初始化为这样:
b->numStorage = 1000000; // Or set more intelligently
Box *b = malloc(sizeof(Box));
// Create an array of pointers
b->storage = calloc(b->numStorage,sizeof(void *));
为了设置该字符串,我用这个函数:
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);
}
问题在于,当我尝试再次检索它,使用完全相同的偏移量:
// 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;
}
返回的指针是乱码。什么可能是错误的?
好点,我修正了numStorage位。 – Rio 2011-04-24 17:29:35