【发布时间】:2011-08-11 22:26:58
【问题描述】:
我正在尝试将字符串存储在结构中包含的数组中并访问它,但我遇到了困难。结构如下所示:
typedef struct {
void **storage;
int numStorage;
} Box;
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;
}
返回的指针是乱码。有什么问题?
【问题讨论】:
标签: c pointers c99 struct memcpy