gpt4 book ai didi

c - 如何清理由 "json_object_new_string"创建的 json 对象?

转载 作者:太空狗 更新时间:2023-10-29 15:26:50 24 4
gpt4 key购买 nike

我有以下代码,我想清理由 json_object_new_string() 创建的 json 对象。

#include <json/json.h>
#include <stdio.h>

int main() {
/*Creating a json object*/
json_object * jobj = json_object_new_object();

/*Creating a json string*/
json_object *jstring = json_object_new_string("Joys of Programming");


/*Form the json object*/
json_object_object_add(jobj,"Site Name", jstring);

/*Now printing the json object*/
printf ("The json object created: %sn",json_object_to_json_string(jobj));

/* clean the json object */
json_object_put(jobj);

}

json_object_put(jobj); 是否清除了 jobjjstring

或者我必须单独使用一个干净的 jstringjson_object_put(jstring);

编辑

问题2

如果以这种方式将 jstring 创建到一个函数中,会有什么行为?

#include <json/json.h>
#include <stdio.h>

static void my_json_add_obj(json_object *jobj, char *name, char *val) {
/*Creating a json string*/
json_object *jstring = json_object_new_string(val);


/*Form the json object*/
json_object_object_add(jobj,name, jstring);
}

int main() {
/*Creating a json object*/
json_object * jobj = json_object_new_object();

my_json_add_obj(jobj, "Site Name", "Joys of Programming")

/*Now printing the json object*/
printf ("The json object created: %sn",json_object_to_json_string(jobj));

/* clean the json object */
json_object_put(jobj);

}

本例中的 jstring 是函数中的局部变量。 json_object_put(jobj); 是否会清除 jstring(在函数 my_json_add_obj() 中创建)?

最佳答案

json_object_put 将释放对象引用的所有内容。所以是的,在 jobj 上使用该函数来释放整个对象就足够了。

关于c - 如何清理由 "json_object_new_string"创建的 json 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18382897/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com