2012-05-06 11 views
0

私の最後の行を見てください。これをどのように印刷するのですか?どのようにキャストするのですか?私はそれをキャストします(word*)table_p -> buckets_array[0] -> data -> key(word*)table_p -> buckets_array[0] -> data -> frequencyこれはどのように印刷しますか?

typedef struct data_{ 
    char *key; 
    void *data; 
    struct data_ *next; 
}data_el; 

typedef struct hash_table_ { 
    /* structure definition goes here */ 
    data_el **buckets_array; 
} hash_table, *Phash_table; 

typedef struct word_{ 
    char key[WORD_SIZE]; 
    int frequency; 
} word; 

word *new_word; 
new_word = (word *)malloc(sizeof(word)); 

new_word->frequency = 5; 
new_word->key = "Lalalal"; 

Phash_table table_p; 
table_p = (Phash_table)malloc(sizeof(hash_table)); 
table_p->buckets_array = (data_el **)malloc(sizeof(data_el *)*(size+1)); 
table_p->buckets_array[0]->data = (void*)new_word; 

/*Is this right? How do I cast this? (word*) ?*/ 
printf("Key :%s Frequency:%d ",table_p->buckets_array[0]->data->key, 
      table_p->buckets_array[0]->data->frequency); 

答えて

1

Here you go

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

#define WORD_SIZE 1024 

typedef struct data_{ 
    char *key; 
    void *data; 
    struct data_ *next; 
}data_el; 

typedef struct hash_table_ { 
    /* structure definition goes here */ 
    data_el **buckets_array; 
} hash_table, *Phash_table; 

typedef struct word_{ 
    char key[WORD_SIZE]; 
    int frequency; 
} word; 

int main() 
{ 

int size=0; 
word *new_word; 
new_word = (word *)malloc(sizeof(word)); 

new_word->frequency = 5; 
strcpy(new_word->key, "Lalalal"); 
// ^^^^    - ooops! you need to copy lalalal bytes into key[] array 

Phash_table table_p; 
table_p = (Phash_table)malloc(sizeof(hash_table)); 
table_p->buckets_array = (data_el **)malloc(sizeof(data_el *)*(size+1)); 


table_p->buckets_array[0] = (data_el *)malloc(sizeof(data_el)); 
// ^^^^    - ooops! you might need some data_el lol 

table_p->buckets_array[0]->data = (void*)new_word; 


/*Is this right? How do I cast this? (word*) ?*/ 
word* pdata=table_p->buckets_array[0]->data; 
// ^^^^    - the readable way 

printf("Key :%s Frequency:%d ",((word*)(table_p->buckets_array[0]->data))->key, //<--the insane cast way (promote void* data_el.data to a word*) 
      pdata->frequency); 

      return 0; 
} 

幸運:ところで&あなたが探している非常識なキャストに沿って固定し、いくつかのミス!

+0

ありがとう、完全な答えを期待していなかった。 –

+0

noP〜はほとんどあなたの質問からペーストしました;) – violet313

関連する問題