如何为指向结构的指针数组分配内存然后释放它?
how to allocate memory for array of pointers to struct and then free it?
我想为指向结构的指针数组分配 space,所以这就是我所做的。
typedef struct A_example{
struct B_example* B_array[MAX_SIZE];
} A
typedef struct B_example{
int a;
}B
A A_array[MAX_SIZE2];
所以要为 B_Array 的一个元素分配内存 A_array 我这样做:
A_array[current_element].B_array[i] = (struct B_example*)malloc(sizeof(struct B_example));
这是正确的吗?我应该如何为此释放内存?
您的分配似乎是正确的(除了通常给出的不使用 malloc
的 return 的标准建议)。您可以 free
通过 free(A_array[current_element].B_array[i]);
.
是的,如果您不想内存泄漏。
我想为指向结构的指针数组分配 space,所以这就是我所做的。
typedef struct A_example{
struct B_example* B_array[MAX_SIZE];
} A
typedef struct B_example{
int a;
}B
A A_array[MAX_SIZE2];
所以要为 B_Array 的一个元素分配内存 A_array 我这样做:
A_array[current_element].B_array[i] = (struct B_example*)malloc(sizeof(struct B_example));
这是正确的吗?我应该如何为此释放内存?
您的分配似乎是正确的(除了通常给出的不使用 malloc
的 return 的标准建议)。您可以 free
通过 free(A_array[current_element].B_array[i]);
.
是的,如果您不想内存泄漏。