VS2012中的C2059 : How to initialize struct instance?

标签 c visual-studio-2012 gcc struct

我有一个要在 VS2012 中编译的 .c 文件,但出现此错误:

error C2059: syntax error : '.' main.c  

根据我的阅读,这是 VS2012 编译器的一个特定问题,我不会在其他编译器中遇到。不管这是不是真的,我希望这里有人能告诉我如何修复这个编译器错误。如何修改代码以使代码编译且行为相同?

这是我的头文件中的内容:

struct mystruct 
{
    struct someOtherStruct obj2;
    void* ptr1;
    void* ptr2;
    void* ptr3;
};

这就是我在 main.c 中的内容

void* P1 = NULL;
void* P2 = NULL;
void* P3 = NULL;

/* VS2012 complains about this syntax */
static struct mystruct obj = 
{
.ptr1 = P1,
.ptr2 = P2,
.ptr3 = P3,
};


void main(void)
{
    /* Empty for now */
}

最佳答案

VS2013(最后)supports指定的初始值设定项,因此您必须升级编译器才能获得此功能。否则重写您的初始化程序,使其符合 C89。

static struct mystruct obj = 
{
    { /* initialize someOtherStruct members here */ },
    P1,  /* drop the member names */
    P2,
    P3,
};

如果您不想为 someOtherStruct 编写初始化程序,请重新排序 mystruct 的成员,以便编译器自动零初始化 obj2 :

struct mystruct 
{
    void* ptr1;
    void* ptr2;
    void* ptr3;
    struct someOtherStruct obj2;
};

static struct mystruct obj = 
{
    P1,
    P2,
    P3,
};

关于VS2012中的C2059 : How to initialize struct instance?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23986521/

相关文章:

c - 将函数的结果保存到 C 中的变量中

c - C中的二叉树插入

无法在我的 Mac 上编译程序集!

c++ - 从 char** 到 const char** 的隐式转换

c - 如何在我的答案中获得乘号(质因数分解)

c# - 从配置文件启动一个字符串

c# - A 类 DLL 不能转换为 B 类 DLL。 Type A originates.. from in the context LoadFrom

jquery - 0x800a139e - JavaScript 运行时错误 : SyntaxError

gcc - 如何让链接器和加载器在特定路径选择共享库?

c - linux终端使用printk打印数据