gpt4 book ai didi

C 结构初始化 : strange way

转载 作者:行者123 更新时间:2023-12-04 10:50:22 27 4
gpt4 key购买 nike

在阅读我遇到的代码时,结构的以下定义和初始化:

// header file
struct foo{
char* name;
int value;
};

//Implementation file
struct foo fooElmnt __foo;
// some code using fooElmnt
struct foo fooElmnt __foo = {
.name = "NAME";
.value = some_value;
}

这在 C 中意味着什么,它与通常的声明有何不同?

最佳答案

它叫做 designated initialization ,

In a structure initializer, specify the name of a field to initialize with .fieldname = before the element value. For example, given the following structure,

 struct point { int x, y; };

the following initialization

 struct point p = { .y = yvalue, .x = xvalue };

is equivalent to

 struct point p = { xvalue, yvalue };

如果您继续阅读,它会解释 .fieldname 被称为 designator .

更新:我不是 C99 专家,但我无法编译代码。这是我必须做出的改变:

// header file
struct foo{
char* name;
int value;
};

//Implementation file
//struct foo fooElmnt __foo;
// some code using fooElmnt
struct foo fooElmnt = {
.name = "NAME",
.value = 123
};

你能编译它吗?我用了TCC .

关于C 结构初始化 : strange way,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2518914/

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