我试图将一个字符串存储在一个包含在结构中的数组中,并访问它,但我遇到了困难。该结构如下所示:
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;
}
返回的指针是乱码。有什么问题吗?
最佳答案
访问数组时不必指定实际的内存偏移量。只需给它索引,您就会得到正确的元素。
因此,在您的第三个代码块中:
b->storage[offset] = keyValue;
在你的第四个:
char *ptr = b->storage[offset];
if (ptr != NULL) {
printf("Data should be %s\n", ptr);
return ptr;
} else {
return NULL;
}
还有,在第二段代码中,是否设置了b->numStorage
?
关于c - 在结构中分配和访问指向字符串的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5772002/