b2科目四模拟试题多少题驾考考爆了怎么补救
b2科目四模拟试题多少题 驾考考爆了怎么补救

c 链表的定义和使用 cjson 源码阅读笔记(2)

电脑杂谈  发布时间:2017-12-31 09:23:46  来源:网络整理

有了内存管理函数,我们就可以生成我们的 value 节点了。

/* Internal constructor. */
static cJSON *cJSON_New_Item(void) {
    cJSON* node = (cJSON*)cJSON_malloc(sizeof(cJSON));
    if (node) memset(node,0,sizeof(cJSON));
    return node;
}

然后通过再设置具体的类型即生成对应类型的节点。

/* Create basic types: */
cJSON *cJSON_CreateNull(void) {
    cJSON *item=cJSON_New_Item();
    if(item)item->type=cJSON_NULL;
    return item;
}
cJSON *cJSON_CreateTrue(void);
cJSON *cJSON_CreateFalse(void);
cJSON *cJSON_CreateBool(int b) {
    cJSON *item=cJSON_New_Item();
    if(item)item->type=b?cJSON_True:cJSON_False;
    return item;
}
cJSON *cJSON_CreateNumber(double num) {
    cJSON *item=cJSON_New_Item();
    if(item) {
        item->type=cJSON_Number;
        item->valuedouble=num;
        item->valueint=(int)num;
    }
    return item;
}
cJSON *cJSON_CreateString(const char *string) {
    cJSON *item=cJSON_New_Item();
    if(item) {
        item->type=cJSON_String;
        item->valuestring=cJSON_strdup(string);
    }
    return item;
}
cJSON *cJSON_CreateArray(void);
cJSON *cJSON_CreateObject(void);

上面我们看到一个 cJSON_strdup 函数, 简单的理解就是复制字符串,返回新的字符串的指针。

删除节点很简单, 先删除儿子,然后清理内存即可。

总结一下就是对于 object 和 array 需要先删除儿子,然后删除自己。

对于 字符串, 需要先释放字符串的内存, 再释放自己这块内存。

对于其他节点,直接释放自己这块内存。

/* Delete a cJSON structure. */
void cJSON_Delete(cJSON *c) {
    cJSON *next;
    while (c) {
        next=c->next;
        if (!(c->type&cJSON_IsReference) && c->child) cJSON_Delete(c->child);
        if (!(c->type&cJSON_IsReference) && c->valuestring) cJSON_free(c->valuestring);
        if (c->string) cJSON_free(c->string);
        cJSON_free(c);
        c=next;
    }
}


本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-57098-2.html

相关阅读
    发表评论  请自觉遵守互联网相关的政策法规,严禁发布、暴力、反动的言论

    热点图片
    拼命载入中...