我在C中有以下结构
struct _MY_LIST
{
short sRecNum;
short sConfirm;
short sFCount;
}my_list;
Run Code Online (Sandbox Code Playgroud)
如何使用malloc为此结构分配内存以及将此结构写入动态内存?
您已经定义了一个由结构组成的结构和变量,但您需要定义一个指向该结构的指针.
指针是一个难以掌握的主题,我即将发布的内容会给你一把锋利的刀 - 但如果你不轻易踩踏,你最终可能会用它来削减自己!学习它们将不仅仅需要一个SO答案,但至少一定要阅读我在这段代码中添加的评论.
struct _MY_LIST
{
short sRecNum;
short sConfirm;
short sFCount;
} *my_list_pointer; /* the asterisk says this is a pointer */
/* dynamically allocate the structure */
my_list_pointer = malloc(sizeof(*my_list_pointer));
/* required error checking! */
if (my_list_pointer == NULL) {
/* do whatever you need, but do _not_ dereference my_list_pointer */
exit(-1);
}
/* write to the structure */
my_list_pointer->sRecNum = 50;
/* read from the structure */
short the_record_number = my_list_pointer->sRecNum;
/* when finished with the allocation, you must release it */
free(my_list_pointer);
/* now, you must NOT dereference my_list_pointer anymore unless you malloc it again! */
Run Code Online (Sandbox Code Playgroud)