2011-11-14 49 views
0

以下是我目前的代碼。我的教授告訴我們使用雙指針創建的指針c雙指針陣列

struct dict { 
    struct word **tbl; 
    int (*hash_fcn)(struct word*); 
    void (*add_fcn)(struct word*); 
    void (*remove_fcn)(struct word*); 
    void (*toString_fcn)(struct word*); 
}; 

struct word { 
    char *s; 
    struct word *next; 
}; 

結構字典* hashtbl的數組;

主要功能

hashtbl=malloc(sizeof(struct dict)); 
    hashtbl->tbl=malloc(sizeof(struct word)*256); 
    int i; 
    for(i=0;i<256;i++) 
    { 
    hashtbl->tbl[i]=NULL; 
    } 

這是實現這種雙指針數組的正確方法的一部分?

並使用

hashtbl->tbl[i] = ..... 

訪問該空間的正確方法嗎?

+0

你想你的指針數組什麼指向? – darksky

+0

它應該指向結構字 – Kamran224

+0

所以初始化'struct word ** tbl'? – darksky

回答

3

hashtbl->tbl=malloc(sizeof(struct word)*256);

實際上應該是

hashtbl->tbl=malloc(sizeof(struct word *)*256);

因爲hashtbl->tblstruct word *

0

陣列要初始化struct word **tbl

hashtbl->tbl = malloc(sizeof(struct word *)*256); 

if (hashtbl->tbl == NULL) { 
    printf("Error malloc"); 
    exit(1); 
} 

for (int i = 0; i < 256; i++) { 
    hashtbl->tbl[i] = malloc(sizeof(struct word)); 
    if (hashtbl->tbl[i] == NULL) { 
     printf("Error malloc"); 
     exit(1); 
} 

解除分配:

for (int i = 0; i < 256; i++) { 
    free(hashtbl->tbl[i]); 
} 
free(hashtbl->tbl); 
hashtbl->tbl = NULL;