【发布时间】:2017-10-24 21:29:37
【问题描述】:
我对 C 很陌生,只是偶然发现了复合文字,所以如果我的问题不准确,请纠正我。
我有一个结构体;
typedef struct
{
int someVal;
} foo;
现在我知道这可以用以下方式初始化。
int main()
{
foo thisFoo = (foo) { .someVal = 2 };
}
我的问题是,我可以用 void 函数初始化 someVal 吗?
void init(int *f);
int main()
{
foo thisFoo = (foo) { init(.someVal) }; // error: expected expression before '.' token
}
void init(int *f)
{
*f = 2;
}
我已经成功地在一个函数中初始化了结构本身及其各自的成员,没有任何问题,但我很好奇这是否是一种替代(甚至是合理的)选择?
【问题讨论】:
-
foo thisFoo; init(&thisFoo.someVal);...void init(int *f) { *f = 2; } -
@BLUEPIXY 我认为他不想让函数知道结构。
-
@Barmar 当然,我修改了评论。
标签: c struct compound-literals