用 C 初始化全局结构 [英] Initializing a Global Struct in C

查看:28
本文介绍了用 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
", a.x);
    return 0;
}

当我尝试编译上述代码时,编译器报如下错误:

When I try to compile the above code, the compiler reports the following error:

初始化元素不是常量"

糟糕的是这条线:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆