gpt4 book ai didi

c - c/Linux 中的自动结构初始化

转载 作者:太空宇宙 更新时间:2023-11-04 09:57:04 25 4
gpt4 key购买 nike

我回到了 c/Linux。这个问题可能看起来很愚蠢,但在使用 C# 等语言之后是相关的。

我在结构内部有一些结构,层次结构级别超过 5。在这种情况下,我在开始时明确地对每个结构进行初始化。我知道 c 没有 new() 方法可以为你做这件事。现在我想知道是否有任何工具/小部件可以为我创建这个启动结构的代码。这是一项乏味的工作,但可以加快我的工作速度。

最佳答案

如果您只想将所有内容初始化为零,您可以使用 {0} 初始化您的 struct,它总是会将所有内容初始化为 0

来自 C 标准,6.7.8(强调我的):

20. If the aggregate or union contains elements or members that are aggregates or unions, these rules apply recursively to the subaggregates or contained unions. If the initializer of a subaggregate or contained union begins with a left brace, the initializers enclosed by that brace and its matching right brace initialize the elements or members of the subaggregate or the contained union. Otherwise, only enough initializers from the list are taken to account for the elements or members of the subaggregate or the first member of the contained union; any remaining initializers are left to initialize the next element or member of the aggregate of which the current subaggregate or contained union is a part.

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.

简而言之,{0} 是任何聚合类型的正确初始值设定项。因此,struct foo bar = { 0 };bar 的第一个元素初始化为 0,其余元素递归初始化为各自的零值(value)观。

如果要将成员初始化为非零值,您可能需要编写一个函数。请注意,“零”值对于每种数据类型都是正确的。对于指针和/或浮点值,这可能不是全零位。

gcc-Wall 选项默认情况下会在您没有“足够”的大括号时发出警告,但如果您知道自己在做什么,则警告是无害的。您可以使用 -Wno-missing-braces

禁用

关于c - c/Linux 中的自动结构初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2414471/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com