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

C/C++ : Pointer on Pointer on structure

本文关键字:指针 结构上 C++      更新时间:2023-10-16

我有 2 个结构:

struct A {
  int m1;
  int m2;
}
第二个结构体作为

前一个结构的成员:

struct Temp_A {    
  A a;    
}

然后我在我的程序中有:

Temp_A** temp_a;

所以我的问题是:

  1. 如何为temp_a分配内存?

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

谢谢!

如何为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 

首先,您必须声明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