我有2个结构:
struct A {
int m1;
int m2;
}
和第二个结构,它具有前一个结构的成员:
struct Temp_A {
A a;
}
然后我在我的程序中:
Temp_A** temp_a;
所以我的问题是:
如何为temp_a
分配内存?
如何访问a
?它应该是某种(* temp_a) - > a ...
谢谢!
答案 0 :(得分:2)
如何为temp_a分配内存?
//1 here is number of pointer elements you want as temp_a is pointer to pointer
// or for simplicity array of pointers.
temp_a = malloc(sizeof(*temp_a)* 1);
//then you should allocate temp_a[0] too
temp_a[0] = malloc(sizeof(**temp_a));
如何访问
(*temp_a)->a
//and tehn
(*temp_a)->a.m1
//you can access as too
temp_a[0]->a
答案 1 :(得分:0)
首先,您必须声明Temp_A
如下:
struct Temp_A {
struct A a;
}
现在,Temp_A**
指向指向Temp_A
的指针,因此您可以指定
temp_a = malloc(sizeof(Temp_A*));
(*temp_a) = malloc(sizeof(Temp_A));
您可以访问
(*temp_a)->a