I want to allocate space for an array of pointers to structs so here is what I did.
我想为一个指向结构的指针数组分配空间,所以这就是我所做的。
typedef struct A_example{
struct B_example* B_array[MAX_SIZE];
} A
typedef struct B_example{
int a;
}B
A A_array[MAX_SIZE2];
so to allocate memory for B_Array for an element of A_array I do this:
所以为A_array的元素分配B_Array的内存我这样做:
A_array[current_element].B_array[i] = (struct B_example*)malloc(sizeof(struct B_example));
is this correct? and how should I free the memory for this?
它是否正确?我应该如何释放内存呢?
2 个解决方案
#1
2
Your allocation appears to be correct (aside from the standard advice that is normally given to not cast the return of malloc
). You can free
it via free(A_array[current_element].B_array[i]);
.
您的分配似乎是正确的(除了通常给出的不会转换malloc的标准建议)。你可以通过免费(A_array [current_element] .B_array [i]);释放它。
#2
0
Yes, if you don't want to have a memory leak.
是的,如果你不想让内存泄漏。
#1
2
Your allocation appears to be correct (aside from the standard advice that is normally given to not cast the return of malloc
). You can free
it via free(A_array[current_element].B_array[i]);
.
您的分配似乎是正确的(除了通常给出的不会转换malloc的标准建议)。你可以通过免费(A_array [current_element] .B_array [i]);释放它。
#2
0
Yes, if you don't want to have a memory leak.
是的,如果你不想让内存泄漏。