指向C中结构变量指针的指针 [英] Pointer to pointer to variable of struct in C
本文介绍了指向C中结构变量指针的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有:
typedef struct a{
int var;
}aa;
typedef struct b{
aa *a;
}bb;
int main()
{
bb *b;
b->a->var;
return 0;
}
struct a
嵌套在 b
中.如何使用 2
指针初始化变量 var
的值,如下所示:b->a->var;
?
struct a
nested in b
.
How to initialize value for variable var
using 2
pointers like this:
b->a->var;
?
推荐答案
- 将
b
初始化为一个有效的指针. - 将
b->a
初始化为一个有效的指针. - 初始化
b->a->var
.
- Initialize
b
to a valid pointer. - Initialize
b->a
to a valid pointer. - Initialize
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;
}
这篇关于指向C中结构变量指针的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文