我试图通过函数中的复合文字来初始化 struct .在解决了我的问题的一部分(参见Use of compound literal inside a function to init a variable in C)之后,我遇到了一个新问题,其中一个成员(ptr_mb
)必须是指向变量的指针.
这是我们的密码:
typedef struct {
int i_mb;
int * ptr_mb;
} my_struct_t;
void init_struct(my_struct_t **my_struct, int * const ptr) {
*my_struct=&(static my_struct_t) {.i_mb=3, .ptr_mb= ptr};
}
int main() {
int a;
my_struct_t *my_struct;
// my_struct = &(my_struct_t) {.i_mb=3, .ptr_mb=&a}; It is OK
// Try to initialize it in a function
init_struct(&my_struct, &a);
}
在main()
,它工作(cf注释行在程序中)
发出编译错误.在函数init_struct
,ptr is not a constant(行:*my_struct=&(static my_struct_t) {.i_mb=3, .ptr_mb= ptr};
)中.
a
是在main()
中声明的变量.因此,它的地址是不变的.我试着用(int const *)
,(int * const)
,(int const * const)
,...有时这是废话,但只是try 和没有工作.
有没有可能在函数中进行这样的初始化,就像在main()
中的工作方式一样?
(Rq. static
使用我知道这是一个C23标准,而且该标准尚未发布;详细信息,请参见以下答案:Use of compound literal inside a function to init a variable in C.