指向C中struct变量的指针
我有 :
typedef struct a{
int var;
}aa;
typedef struct b{
aa *a;
}bb;
int main()
{
bb *b;
b->a->var;
return 0;
}
struct a嵌套在b. 如何初始化变量值var使用2指针这样的:
b->a->var;
?
回答
- 初始化
b为有效指针。 - 初始化
b->a为有效指针。 - 初始化
b->a->var。
#include <stdlib.h>
typedef struct a{
int var;
}aa;
typedef struct b{
aa *a;
}bb;
int main(void)
{
bb *b;
/* initialize b */
b = malloc(sizeof(*b));
if (b == NULL) return 1;
/* initialize b->a */
b->a = malloc(sizeof(*b->a));
if (b->a == NULL)
{
free(b);
return 1;
}
/* initialize b->a->var */
b->a->var = 42;
/* free what are allocated */
free(b->a);
free(b);
return 0;
}