我在C
中有以下结构struct _MY_LIST
{
short sRecNum;
short sConfirm;
short sFCount;
}my_list;
如何使用malloc为此结构分配内存以及将此结构写入动态内存?
答案 0 :(得分:5)
您已经定义了一个由结构组成的结构和变量,但您需要定义一个指向该结构的指针。
指针是一个难以掌握的主题,我即将发布的内容会给你一把锋利的刀 - 但如果你不轻易踩踏,你最终可能会用它来削减自己!学习它们将需要远远超过一个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! */
答案 1 :(得分:1)
#include <stdlib.h>
struct _MY_LIST
{
short sRecNum;
short sConfirm;
short sFCount;
}my_list;
void main()
{
my_list * list;
list = (my_list*) malloc(sizeof(my_list))
my_list->sRecNum = 1;
my_list->sConfirm = 2;
my_list->sFCount = 3;
free(list);
}
永远不要忘记释放指针。 我可以避免它在ansi-c中不使用malloc和free。
如果您的来源可以使用,可以选择以下选项。
struct _MY_LIST
{
short sRecNum;
short sConfirm;
short sFCount;
}my_list;
void uselist(my_list * list);
void main()
{
my_list list;
uselist(&list);
}
void uselist(my_list * list)
{
list->sRecNum = 1;
list->sConfirm = 2;
list->sFCount = 3;
}
答案 2 :(得分:0)
首先,不要使用以下划线开头的标识符,因为它们可能会与为C
的实现保留的标识符发生冲突,正如Jens在评论中所提到的那样。
struct myList {
short sRecNum;
short sConfirm;
short sFCount;
};
struct myList foo;
以上定义了struct myList
类型的结构。现在,您可以像使用type identifier;
这样的任何其他类型一样定义此类型的变量。您可以将两者结合起来并定义一个结构,并在与
struct myList {
short sRecNum;
short sConfirm;
short sFCount;
} foo;
要为变量动态分配内存,请使用标头malloc
中声明的stdlib.h
。
void *malloc(size_t size);
此处,size
是要分配的字节数,size_t
是一种类型(typedef
,因此_t
)来表示计算机上对象的大小。它返回一个类型为void *
的指针,它是指针的泛型类型。 void *
分配与任何指针类型兼容,因此您不应该转换malloc
的结果。 malloc
如果没有&#39则无法分配内存;足够的可用。每次拨打malloc
时都需要检查。
使用sizeof
运算符查找类型或变量的大小(以字节为单位)。请注意,当sizeof
的操作数是变量时,您不需要使用括号。
struct myList *bar = malloc(sizeof *bar);
if(bar == NULL) {
// memory allocation failed.
// handle it
}
else {
// assign values to the structure members
bar->sRecNum = 1;
bar->sConfirm = 2;
bar->sFCount = 3;
// do stuff with bar
// after you are done free the memory allocated by malloc
// it is a good practice to set bar to NULL after freeing it
free(bar);
bar = NULL;
}