2011-04-24 102 views
0

我试图在一个包含在一个结构中的数组中存储一个字符串,并访问它,但我很难。该结构是这样的:分配和访问结构中指向字符串的指针

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; 
    } 

返回的指针是乱码。什么可能是错误的?

回答

2

访问数组时不必指定实际的内存偏移量。简单地给它索引,你会得到正确的元素。

所以,在你的第三代码块:

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已经设置?

+0

好点,我修正了numStorage位。 – Rio 2011-04-24 17:29:35

2
b->storage[offset*sizeof(void *)] = &keyValue; 

这将本地变量keyValue的地址存储在数组中。该功能完成后,该地址变为无效。我想你想:

b->storage[offset*sizeof(void *)] = keyValue; 

然后在检索时做出相应的改变。

1

不这样:

b->storage[offset*sizeof(void *)] = &keyValue 

组存储[偏移量*的sizeof(无效*)]来指向本地变量的keyValue的地址?即函数返回后不再有效