如何在C语言中编辑结构体内的多个变量

huangapple go评论92阅读模式
英文:

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 };

huangapple
  • 本文由 发表于 2023年8月9日 17:22:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76866306.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定