gpt4 book ai didi

C 数据隐藏在结构中 : an explanation

转载 作者:太空宇宙 更新时间:2023-11-04 08:39:37 25 4
gpt4 key购买 nike

我有这种情况:
我试图以这种方式混淆一些数据

/* item.h */
typedef struct ItemStruct *Item;

/*item.c*/
#include "item.h"

struct ItemStruct
{
char word[MAXSTRING];
int number;
};

Item ItemGet()
{
Item i;

i = (Item) malloc (sizeof(*i));
if (i == NULL)
{
fprintf ( stderr, "Error: insufficient memory for new element.\n");
return NULL;
}

return i;
}

好吧,我使用了 friend 解决方案中的这个 malloc:

i = (Item) malloc (sizeof(*i));

但一开始我是这样写的:

i = (Item*) malloc (sizeof(Item));

这会在我用于分配的每个“sizeof”处给我一个“不完整类型”错误。
我问你为什么,因为我不明白这个。

最佳答案

Item 被定义为新类型指向结构 ItemStruct 的指针。 sizeof(Item) 将给出指向结构 ItemStruct 的指针的大小,而不是结构本身的大小。试试这个

i = malloc (sizeof(ItemStruct)); // or malloc (sizeof(*i))

关于转换,malloc 返回void * 并且它可以分配给任何指针而无需显式转换和never cast the return value of malloc .

关于C 数据隐藏在结构中 : an explanation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24350315/

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