有了内存管理函数,我们就可以生成我们的 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
你是厂家派来的逗比吗
那还不感觉用鱼雷