结构中的结构的c-malloc数组



我有一个名为课程的结构,每个课程都有多个节点(另一个结构"node")。

它的节点数量各不相同,但我从读取这些信息的文件中得到了这个数字,所以这个数字位于一个变量中。

所以我需要在结构中使用malloc。但我很困惑。我知道你可以在structs中有数组,但我不知道把创建malloc数组的代码放在哪里,因为我的structs在我的头文件中。这是我现在的密码。我意识到它看起来是错误的,我只是不知道如何修复它,以及在哪里初始化malloc数组。

struct course {
char identifier[2];
int num_nodes;
struct node *nodes;
nodes = (struct nodes*)malloc(num_nodes*sizeof(struct node));
};
struct node {
int number;
char type[2];
};

我想做一些类似的事情:

struct node a_node;
struct course a_course;
a_course.nodes[0] = a_node;

等等。。。

我没有使用太多的C,这是我第一次尝试在C中使用动态数组。我的经验都来自Java,当然Java并不像C那样真正使用指针,所以这对我来说有点困惑。

因此,我们将非常感谢您的帮助,非常感谢:)

最简单的方法是创建一个初始化结构的函数:

void init_course(struct course* c, const char* id, int num_nodes)
{
strncpy(c->identifier, id, sizeof(c->identifier));
c->num_nodes = num_nodes;
c->nodes = calloc(num_nodes, sizeof(struct node));
}

对于对称性,你也可以定义一个析构函数

void destroy_course(struct course* c)
{
free(c->nodes);
}

这些将具有类似的用途

struct course c;
init_course(&c, "AA", 5);
/* do stuff with c */
destroy_course(&c);

malloc(或calloc,我更喜欢用于结构)的目的是在运行时动态分配内存。因此,您的结构应该是这样的,因为它是一个对象定义:

struct course {
char identifier[2];
int num_nodes;
struct node *nodes;
};

在使用课程结构的程序中的其他地方,您将需要为(i)创建的任何课程对象和(ii)该课程中的任何节点对象分配内存。

例如

main()
{
// lets say 1 course
struct course *my_course;
my_course = calloc(1, sizeof(struct course));
// lets say 3 nodes in that course
struct node *my_nodes;
my_nodes = calloc(3, sizeof(struct node));
my_course.num_nodes = 3;
my_course.nodes = my_nodes;
//...
// clean up
free(my_nodes);
free(my_course);
}

现在,你很好。退出前请确保释放内存。

也可以通过以下方式直接分配结构中的结构:

首先声明您的结构:

struct course {
char identifier[2];
int num_nodes;
struct node *nodes;
};

然后在你的程序

main(){ 
int i;
struct course *c;
c = malloc(sizeof(struct course));
c->num_nodes = 3;
c->nodes = malloc(sizeof(struct node)*c->num_nodes);
for(i=0; i<c->num_nodes; i++) 
c->nodes[i] = malloc(sizeof(struct node));
//and free them this way
for(i=0; i<c->num_nodes; i++) 
free(c->nodes[i]);
free(c->nodes);
free(c);

}

或者按照你喜欢的

最新更新