- 论坛徽章:
- 0
|
本帖最后由 wcybxzj 于 2014-05-01 03:39 编辑
模拟redis 字典结构但我写的代码确报段错误
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct dictEntry {
int key;
} dictEntry;
typedef struct dictht {
dictEntry **table;
int d_val;
} dictht;
typedef struct dict {
dictht ht[2];
} dict;
dict *dictCreate();
int dictInit(dict *d);
static void dictReset(dictht *ht);
dict *dictCreate()
{
dict *d = malloc(sizeof(*d));
dictInit(d);
return d;
}
int dictInit(dict *d)
{
dictReset(&d->ht[0]);
dictReset(&d->ht[1]);
return 0;//ok
}
static void dictReset(dictht *ht)
{
ht->table = NULL;
ht->d_val = 0;
}
static void add_ht(dict *d,int val)
{
dictht *ht;
ht = &d->ht[0];
dictEntry *dict_entry=malloc(sizeof(dictEntry)*1);
dict_entry->key=123;
//ht->table=dict_entry;//this will fine
ht->table[0]=dict_entry;//this will cause "Segmentation fault" 为什么??
return;
}
void add_to_ht(dict *d,int val){
add_ht(d,val);
}
int main(int argc, const char *argv[])
{
dict *d = malloc(sizeof(*d));
d=dictCreate();
//add
add_to_ht(d,22);
//printf("%d\n",d->ht[0].table[0]->key);
//printf("%d\n",&d->ht[1].table[0]);
return 0;
}
|
|