C / C ++:指针结构上的指针

时间:2014-02-21 12:37:07

标签: c++ c pointers struct

我有2个结构:

struct A {
  int m1;
  int m2;
}

和第二个结构,它具有前一个结构的成员:

struct Temp_A {    
  A a;    
}

然后我在我的程序中:

Temp_A** temp_a;

所以我的问题是:

  1. 如何为temp_a分配内存?

  2. 如何访问a?它应该是某种(* temp_a) - > a ...

  3. 谢谢!

2 个答案:

答案 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