在cjson调用时遇到的结构体参数赋值时的问题,需要cJSON**才行,下面两种方法都行,对比一下。
也对指针理解更深入:
结构体给函数当形参时,由于主函数里也没分配结构体空间,只有结构体的地址,局部函数里面只能给局部结构体地址,给结构体的地址放在结构体地址的空间中,要有存放结构体地址空间的地址,也就是下面例子中的cJSON**
#include <stdlib.h>
#include "cJSON.h"
/* Parse text to JSON, then render back to text, and print! */
//1、使用返回值进行,返回jSON*
/* cJSON *doit(char *text)
{
char *out;//cJSON *json;
int flag = 0;
cJSON *c = cJSON_Parse(text);
//printf("text = %s\n", text);
return c;
}
*/
//2、使用jSON**给形参
void doit2(char *text,cJSON** root)
{
char *out;
*root = cJSON_Parse(text);
printf("doit2 text = %s\n", text);
}
int main (int argc, const char * argv[])
{
/* a bunch of json: */
char sensorValue[] = "{\"WIFIessid\":[{\"ESSID\":\"ylst-s\"},{\"ESSID\":\"mordenmansion\"},{\"ESSID\":\"ChinaNet-wvQS\"},{\"ESSID\":\"CMCC\"},{\"ESSID\":\"CMCC-AUTO\"},{\"ESSID\":\"beacon05\"},{\"ESSID\":\"cnswx\"}]}";
//cJSON *root = (cJSON*)malloc(sizeof(cJSON));
//1、使用返回值进行,返回cJSON*
/* cJSON *root;
char *out;
root = doit(sensorValue);
printf("222 root->type = %d\n", root->type);
out=cJSON_Print(root);
cJSON_Delete(root);
printf("doit:%s\n",out);
*/
//2、使用cJSON**给形参
cJSON *root;
char *out;
doit2(sensorValue,&root);
printf("222 root->type = %d\n", root->type);
out=cJSON_Print(root);
cJSON_Delete(root);
printf("doit2:%s\n",out);
//char * out= NULL;printf("AAABBB\n");
//out = cJSON_Print(root);printf("AAABBB\n");
//printf("AAAAAAAAAAA\n%s\n",out);
return 0;
}