结构体指针作为函数参数的应用

xiaoxiao2021-02-28  13

一、结构体的多层封装

在头文件中进行声明:

typedef struct { char summary[45]; char datetime[20]; char repeat_type[10]; char voice_data_url[125]; char voice_file_id[40]; unsigned char voice_type; }SCHEDULE_ITEM_UPDATE;

typedef struct { unsigned char total_item; unsigned char downloaded_item; SCHEDULE_ITEM_UPDATE schedule_item_updated[5]; }SCHEDULE_ITEM;

在c文件中进行定义:SCHEDULE_ITEM schedule_item={0};

在头文件中进行声明:extern SCHEDULE_ITEM schedule_item;

二、定义函数

int cJSON_to_struct_array(char *text, SCHEDULE_ITEM *pst) { cJSON *json, *arrayItem, *item, *object; int i; BaseType_t err=NULL; json = cJSON_Parse(text); if (!json) { printf("Error before: [%s]\n", cJSON_GetErrorPtr()); } else { int size = cJSON_GetArraySize(json); printf("cJSON_GetArraySize: size=%d\n", size); //schedule_item.total_item=size; pst->total_item=size; printf("schedule_item.total_item=%d\r\n",schedule_item.total_item); schedule_item_updated_cnt=0; for (i = 0; i<size; i++) { printf("i=%d\n", i); object = cJSON_GetArrayItem(json, i); item = cJSON_GetObjectItem(object, "repeat_type"); if (item != NULL) { printf("cJSON_GetObjectItem: type=%d, string is %s,valuestring=%s\n", item->type, item->string, item->valuestring); memcpy(pst->schedule_item_updated[i].repeat_type, item->valuestring, strlen(item->valuestring)); } item = cJSON_GetObjectItem(object, "voice_file_id"); if (item != NULL) { printf("cJSON_GetObjectItem: type=%d, string is %s, valuestring=%s\n", item->type, item->string, item->valuestring); memcpy(pst->schedule_item_updated[i].voice_file_id, item->valuestring, strlen(item->valuestring)); } item = cJSON_GetObjectItem(object, "datetime"); if (item != NULL) { printf("cJSON_GetObjectItem: type=%d, string is %s, valuestring=%s\n", item->type, item->string, item->valuestring); memcpy(pst->schedule_item_updated[i].datetime, item->valuestring, strlen(item->valuestring)); } item = cJSON_GetObjectItem(object, "voice_data_url"); if (item != NULL) { printf("cJSON_GetObjectItem: type=%d, string is %s, valuestring=%s\n", item->type, item->string, item->valuestring); memcpy(pst->schedule_item_updated[i].voice_data_url,item->valuestring, strlen(item->valuestring)); } else { printf("cJSON_GetObjectItem: get age failed\n"); } item = cJSON_GetObjectItem(object, "summary"); if (item != NULL) { printf("cJSON_GetObjectItem: type=%d, string is %s, valuestring=%s\n", item->type, item->string, item->valuestring); memcpy(pst->schedule_item_updated[i].summary,item->valuestring, strlen(item->valuestring)); } } for (i = 0; i<size; i++) { err=xSemaphoreGive(CountSemaphore);// printf("xSemaphoreCreateCounting:CountSemaphore ...\n"); } cJSON_Delete(json); } return 0; }三、引用

 

cJSON_to_struct_array(mqtt_data_for_pro, &schedule_item);四、说明:

注意,因为是使用结构体指针作为函数参数,所以在对结构体内的成员变量进行修改时,使用的是->符号。而且对于数组而言,常采用memcpy()函数进行操作。

转载请注明原文地址: https://www.6miu.com/read-1650170.html

最新回复(0)