免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2554 | 回复: 1
打印 上一主题 下一主题

[C] redis 代码中的问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2014-05-01 03:37 |只看该作者 |倒序浏览
本帖最后由 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;
}

论坛徽章:
0
2 [报告]
发表于 2014-05-01 23:51 |只看该作者
ht->table=dict_entry;改为ht->table=&dict_entry;
因为你的table是二级指针
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP