你想这样做:
#include <stdio.h>
#include <stdlib.h>
struct test {
struct foo **val;
};
struct foo {
int a;
};
int main(void) {
struct test* test_ptr = malloc(sizeof(struct test));
struct foo* foo_ptr = malloc(sizeof(struct foo));
foo_ptr->a = 5; // equivalent to (*foo_ptr).a = 5;
test_ptr->val = &foo_ptr;
printf ("Value of a is %d\n", (*(test_ptr->val))->a);
free(test_ptr);
free(foo_ptr);
return 0;
}
输出:
C02QT2UBFVH6-lm:~ gsamaras$ gcc -Wall main.c
C02QT2UBFVH6-lm:~ gsamaras$ ./a.out
Value of a is 5
在我的例子中:
- 我为 a 动态分配空间
struct test
。
- 我为 a 动态分配空间
struct foo
。
- 我将值 5 分配给 的
a
成员foo_ptr
。
- 我将分配对象的地址分配给的
struct foo
成员val
。test_ptr
- 我打印成员
a
双指针val
指向的结构。
请注意,在您的示例中:struct foo
是一种类型,因此询问其地址是没有意义的。
此外,当您完成声明struct foo
.
哦,请确保不要强制转换 malloc() 的返回值。