2012-02-06 100 views
0

新手在這裏,將數據存儲在地址中並更改C中變量的地址?

我有一個詞,它包含了文字本身字符數組一個結構(該結構具有其它功能,這無關我的問題),我試圖將其存儲在一個hashmap,它是一個字結構指針數組。在我的程序中,每次看到一個新單詞時,都會創建一個新字struct和malloc char-array來創建它。但是,循環過幾次之後,它會將舊單詞更改爲新單詞,即使它位於不同的散列映射位置。

我想知道的是,如果有可能讓我創建新的字結構指向新地址的循環?

struct words add; 
int b; 
for(b = 0; b < strlen(LowerCaseCopy); b++) 
{ 
    add.word[b] = '\0'; 
} 
for(b=0;b< strlen(LowerCaseCopy);b++) 
{ 
add.word[b] = LowerCaseCopy[b]; 
} 
hashmap[hashf] = &add; 

這是有問題的代碼。

我的問題的一個例子: 循環的第一個runthrough,我將add.word設置爲Apple,它存儲在特定的hashmap插槽中。 循環的下一個runthrough,我將add.word設置爲橙色,它存儲在不同的插槽。問題是,在第一個插槽,它不再存儲蘋果,而是存儲橙色,所以我有2個存儲橙色的插槽,這不是我想要的。我該如何解決?

+0

你如何獲得'hashf'的值?它有沒有改變? – Philip 2012-02-06 07:06:22

+0

使用'b 2012-02-06 07:08:24

+0

是的,hashf正在改變,這只是我的代碼的一部分,我有這個部分在一個循環中。如果我在循環的每次迭代中重用該變量,是否不會更改地址? – Kevin 2012-02-06 07:13:06

回答

0

一個簡單的解決方案(我認爲)將把功能添加到散列映射到一個單獨的函數。如果您刪除的條目

void add_to_hashmap(struct something *hashmap, char *lower_case_word) 
{ 
    /* Using "calloc" we don't have to manually clear the structure */ 
    struct words *words = calloc(1, sizeof(struct words)); 

    /* Copy +1 to include the terminating '\0' */ 
    memcpy(words->word, lower_case_word, strlen(lower_case_word) + 1); 

    /* Replace this with whatever you use to calculate the hash */ 
    int hashf = calculate_hash(lower_case_word); 

    hashmap[hashf] = words; 
} 

(即其設置爲NULL)你要記得先釋放它:該函數分配一個新的words結構,並提出,在HashMap中。

+0

太棒了!如果可以的話,我會擁抱你!非常感謝!感謝你的幫助 – Kevin 2012-02-06 13:10:55