c - 为什么编译器会抛出这个警告 : "missing initializer"? Is the structure initialized?

标签 c winapi gcc

我正在为程序创建某种前端。为了启动程序,我使用了调用 CreateProcess(),其中接收到一个指向 STARTUPINFO 结构的指针。初始化我曾经做过的结构:

STARTUPINFO startupInfo = {0}; // Or even '\0'.
startupInfo.cb = sizeof(startupInfo);

当使用启用这些警告集的 GCC 编译程序时 -Wall -Wextra 它给了我一个警告,说缺少指向第一行的初始化程序。

warning: missing initializer
warning: (near initialization for 'startupInfo.lpReserved')

所以我最终做了:

STARTUPINFO startupInfo;
memset(&startupInfo, 0, sizeof(startupInfo));
startupInfo.cb = sizeof(startupInfo);

这样编译器就不会给出任何警告。 问题是,这些初始化结构的方式有什么区别? 使用第一种方法,结构体不是初始化了吗? 你会推荐哪一个?

最佳答案

GCC 只是过于偏执 - 在我看来没有充分的理由,但是 GCC 维护者确实比我更了解 C 的细微差别。

请参阅 GCC 邮件列表中有关此问题的小讨论:

但最重要的是 - 仅使用 {0} 初始化结构实际上会将整个事物初始化为零。

C99标准在 6.7.8/21“初始化 - 语义学”中说明如下:

If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

C90 在 6.5.7 中说的基本相同,只是措辞有点不同(换句话说,C99 没有在这里添加新内容)。

另请注意,在 C++ 中,这已得到扩展,因此一组空的大括号“{}”将对对象执行值初始化,因为在某些情况下(如模板)您不会甚至不知道一个类型可能有哪些成员或多少成员。因此,拥有一个比对象可能具有的成员数量短的初始化列表不仅是一种好的做法,而且有时是必要的。

关于c - 为什么编译器会抛出这个警告 : "missing initializer"? Is the structure initialized?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1538943/

相关文章:

while循环的语法可以是一个在开始时没有赋值的变量吗?

c - 结构 - 删除其中一个元素

c++ - 在 ubuntu 14.04 LTS 上编译 fileZilla

c++ - Listview 三态复选框

c++ - 是否可以更改不受您控制的 dll 的默认线程堆栈大小 c++ win32

gcc - 如何在 Mac OS X 主机上为 MIPS 目标构建 GCC 4.8.x

c++ - 在 MinGW/MSYS 上编译 GCC 4.x.x 失败

来回发送的条件变量

c - valgrind 检测到内存泄漏但应用程序工作

windows - 设置透明背景 Win32