c - 将 malloc 与结构和 strcpy 一起使用

标签 c struct malloc strcpy cjson

我正在尝试制作一个名为 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 库,将 nameindexoptional 的字符串值放入上面引用的变量中,并且它们存储在这些变量的 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/

相关文章:

Android NDK 不链接预建库

c++ - 如何从另一个 .cpp 文件访问全局结构?

c++ - 类 C 结构中自动字段重新排序的方法

c - Qsort 对指向另一个结构的结构数组进行排序

c - 为什么当我使用函数分配内存时失败

c - 如何实现calloc

从数据文件读取矩阵,然后计算它们的乘积,然后将结果矩阵打印到数据文件的代码

c - 如何在消息中设置 IPv6 路由器警报选项

c - 为什么函数会根据容量返回不同的值

c - 链表 malloc 内存泄漏