2017-01-16 5 views
-1

에 init_hash, 내가 여기에 문제를 가지고해시 테이블이 내가 얻을 크기에 해시 테이블을 초기화 할 필요가 C

#include <stdio.h> 

typedef struct element{ 
    char * key;  
    char * value;  
}element; 

typedef struct HashTable{ 
    int size; // size of the arr 
    element **arr_table; //arr of elements 
}HashTable; 


void init_hash(int size, HashTable * t) 
{ 
    if (size < 1) 
     return; 
    t->size = size; 
    t->arr_table = (element **)malloc(sizeof(element*)*size); 
    if (t->arr_table == NULL) // out memory 
     return; 
    int i; 
    for (i = 0; i < size; i++) 
    { // initial list 
     t->arr_table[i]->key = NULL; 
     t->arr_table[i]->value = NULL; 
    } 

} 



void main() 
{ 
    HashTable *ht = (HashTable*)malloc(1*sizeof(HashTable)); 
    int size_ht = 9; 
    init_hash(size_ht, ht); 
    printf("...\n"); 
    return; 
} 
+0

"문제가 있습니다." 문제가 정확히 무엇인지 말해주는 것이 합리적이라고 생각하지 않습니까? 그 상식 아닌가요? – kaylum

+0

내가 왜 happaned @ kaylum 모르겠어요 – edenv3

+0

당신은 요소에 대한 포인터의 *** 배열을 만들려고합니까 아니면 *** 배열의 요소가 *** HashTable 구조 안에 있습니까? – user3386109

답변

1

당신이 만든 것은 요소 포인터의 배열입니다 t->arr_table[i]->key = NULL; . 그러나 init_hash 함수는 요소 배열을 기대합니다. 요소의 배열을 만들려면 코드는 아래와 같아야합니다. 일부 변경 사항을 강조하기 위해 몇 가지 설명을 추가했습니다.

typedef struct element{ 
    char *key; 
    char *value; 
}element; 

typedef struct HashTable{ 
    int size; 
    element *arr_table;  // <-- only one '*', not two, to declare a pointer to an array of elements 
}HashTable; 

void init_hash(int size, HashTable *t) 
{ 
    if (size < 1) 
     return; 
    t->size = size; 
    t->arr_table = malloc(sizeof(element) * size); // <-- allocate memory for the elements, note 'sizeof(element)' not 'sizeof(element *)' 
    if (t->arr_table == NULL) 
     return; 
    int i; 
    for (i = 0; i < size; i++) 
    { 
     t->arr_table[i].key = NULL;   // <-- table[i] is a structure, use dot notation 
     t->arr_table[i].value = NULL; 
    } 
} 

int main(void) // <-- declare main with the correct signature 
{ 
    HashTable *ht = malloc(sizeof(HashTable)); // <-- don't cast the return value from malloc 
    int size_ht = 9; 
    init_hash(size_ht, ht); 
    printf("...\n"); 
} 
+0

내부에 요소 배열을 만들려고합니다. 감사합니다. – edenv3