英文:
How to edit multiple variables inside a structure in C
问题
typedef struct
{
string color;
int age;
} Dog;
int main(void)
{
Dog cookie = {"brown", 6};
cookie.color = "blue";
cookie.age = 12;
}
你好,我想知道是否有一种方法可以在只使用一行代码的情况下编辑多个结构体的值,而不是一遍又一遍地重复"structName.varName"。
在C语言中,是否有类似的方法可以更改多个对象的值呢?非常感谢。
英文:
typedef struct
{
string color;
int age;
}Dog;
int main(void)
{
Dog cookie = ("brown", 6);
cookie.color = "blue";
cookie.age = 12;
}
Hello, I'd like to know if there's a way to edit multiple structure values as such,
while only using a single line instead of repeating "structName.varName" over and over.
Would there be a similar method for changing multiple values for objects in C as well? Thank you so much.
答案1
得分: 3
你可以使用"复合字面量"临时对象一次为多个结构成员赋值:
cookie = (Dog) { "blue", 12 };
或者为了增加可读性,可以将其与"指定初始化器"结合使用(等效的代码):
cookie = (Dog) { .color = "blue", .age = 12 };
英文:
You can assign multiple struct members a value at once, by using a compound literal temporary object:
cookie = (Dog) { "blue", 12 };
Or for increased readability, combine this with designated initializers (equivalent code):
cookie = (Dog) { .color = "blue", .age = 12 };
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论