我正在尝试制作一个名为 StatusItem
的结构数组,如下所示:
typedef struct
{
char* name;
char* index;
int optional;
} StatusItem;
此外,由于我希望这个数组具有任意大小,因此我使用了 malloc
。所以数组是这样定义的:
StatusItem* statusItem = NULL;
(然后将其传递给函数,该函数按如下方式检索所有值。)
statusItem = (StatusItem*)malloc(cJSON_GetArraySize(items));
...
for (i = 0 ; i < cJSON_GetArraySize(items) ; i++)
{
strcpy(statusItem[i].name,name->valuestring);
strcpy(statusItem[i].index,index->valuestring);
if(!parseInt(optional->valuestring, &statusItem[i].optional));
{
goto cleanup;
}
}
有代码涉及 cJSON 库,将 name
、index
和 optional
的字符串值放入上面引用的变量中,并且它们存储在这些变量的 valuestring
字段中。
我已经检查过涉及 cJSON 库的所有内容都工作正常,并返回了正确的值,但是程序无法访问或将值存储在 statusItems
数组中。
有什么想法吗?我几乎可以肯定,这涉及到我对 malloc
的一些滥用。
最佳答案
1) cJSON_GetArraySize(items)
返回一个元素计数 - 您需要将对象的大小考虑在内:malloc(cJSON_GetArraySize(items) * sizeof(StatusItem))
2) StatusItem
结构没有实际字符串的内存——只有一个指向字符串的指针。您可以使用 strdup()
分配和复制字符串。
您可能希望您的代码看起来更像:
statusItem = (StatusItem*)malloc(cJSON_GetArraySize(items) * sizeof(StatusItem));
...
for (i = 0 ; i < cJSON_GetArraySize(items) ; i++)
{
statusItem[i].name = strdup(name->valuestring);
statusItem[i].index = strdup(index->valuestring);
if(!parseInt(optional->valuestring, &statusItem[i].optional));
{
goto cleanup;
}
}
当然,这意味着当您释放 StatusItem
对象数组时,您还必须显式释放重复的字符串:
// to free the statusItem array, and the various strings it refers to:
for (i = 0 ; i < cJSON_GetArraySize(items) ; i++)
{
free(statusItem[i].name);
free(statusItem[i].index);
}
free(statusItem);
关于c - 将 malloc 与结构和 strcpy 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16904217/