2011-04-24 98 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的地址?即函數返回後不再有效