Memory 什么时候应该将指针的大小与结构本身的大小进行malloc比较?
我很难理解何时将指针的大小与结构的大小进行malloc比较。例如: 我有一个结构:Memory 什么时候应该将指针的大小与结构本身的大小进行malloc比较?,memory,struct,malloc,Memory,Struct,Malloc,我很难理解何时将指针的大小与结构的大小进行malloc比较。例如: 我有一个结构: typedef struct { char *String; int Length; } WORD; 我想使用指针创建指向单词数组的指针: WORD **WordArray; WordArray = malloc(sizeof(WORD*)) //Since WordArray is only a single ptr to an array of WORDS 现在我需要为数组中的
typedef struct {
char *String;
int Length;
} WORD;
我想使用指针创建指向单词数组的指针:
WORD **WordArray;
WordArray = malloc(sizeof(WORD*)) //Since WordArray is only a single ptr to an array of WORDS
现在我需要为数组中的每个元素分配内存(假设为3):
我是否为这些结构正确分配内存?如果我要最终释放WordArray,我是否需要在释放WordArray之前释放每个元素?您总是malloc对象的大小,并将结果强制转换为指向该对象的指针
因此,如果您
malloc
aT
,则将其转换为T*
。如果T==WORD*
,则将其转换为WORD**
。这个logica也是反向工作的,如果您需要强制转换结果是一个WORD**
,那么对象必须是一个WORD*
好的,所以我的假设是正确的,我只需要malloc一个指向数组的指针(WordArray=malloc(sizeof(WORD*)
)和数组中每个元素的3个结构(*WordArray=malloc(sizeof(WORD)*3);
)?@user1224478:如果您真的需要malloc
指向该数组的指针,那么是的。但我不能从这里说您是否需要第二级。
*WordArray = malloc(sizeof(WORD) * 3); //Need to allocate the actual struct WORD * number of elements in the array