我試圖在一個包含在一個結構中的數組中存儲一個字符串,並訪問它,但我很難。該結構是這樣的:分配和訪問結構中指向字符串的指針
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