在C中初始化全局结构 [英] Initializing a Global Struct in C
本文介绍了在C中初始化全局结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在C语言中完成以下操作的最佳方法是什么?
What is the best way to accomplish the following in C?
#include <stdio.h>
struct A
{
int x;
};
struct A createA(int x)
{
struct A a;
a.x = x;
return a;
}
struct A a = createA(42);
int main(int argc, char** argv)
{
printf("%d\n", a.x);
return 0;
}
当我尝试编译以上代码时,编译器报告以下错误:
When I try to compile the above code, the compiler reports the following error:
初始化器元素不是恒定的
"initializer element is not constant"
糟糕的是:
struct A a = createA(42);
有人可以解释出什么问题吗?我对C语言不太熟悉。谢谢!
Can someone explain what is wrong? I'm not very experienced in C. Thanks!
推荐答案
为什么不使用静态初始化?
Why not use static initialization?
struct A a = { 42 };
这篇关于在C中初始化全局结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文