gpt4 book ai didi

c - 结构员工 {} 比较结构 {} 员工

转载 作者:行者123 更新时间:2023-12-02 06:47:23 25 4
gpt4 key购买 nike

我读了一个教程,其中有这个结构:

struct
{
char Name[25];
int Age;
float SkillRating;
} Employee;

defines a new aggregate, called Employee, containing fields called Name (of type character), Age (of type integer), and SkillRating (of type float).

相比之下,C 语句:

struct EmployeeType
{
char Name[25];
int Age;
float SkillRating;
};

does not define a new aggregate variable, but defines a new aggregate type, EmployeeType. This new data type could then be used to declare variables in the same way as a primitive data type. That is, in the same way that C allows the variable x to be declared as an integer using the statement

我在这里很困惑。 'Emplyee`放在不同的位置有区别吗?

我猜他们是一样的。

最佳答案

在第一种情况下,struct 是未命名的,Employee 是该未命名结构的变量。可以直接这样修改:

int main()
{
Employee.Age = 100;
return 0;
}

在第二种情况下,EmployeeType 只是一个类型,但您还没有创建它的任何实例。您可以创建任意数量的实例:

int main()
{
struct EmployeeType a; // employee on the stack
a.Age = 100;
struct EmployeeType *b = malloc(sizeof(struct EmployeeType)); // employee on the heap
if (b) { // set the age of b if the allocation succeeded
b->Age = 100;
}
free(b); // malloc-allocated memory must be freed afterwards
return 0;
}

你甚至可以同时做这两件事:

struct EmployeeType
{
char Name[25];
int
Age;
float SkillRating;
} Employee;

在这里,Employee 是它的一个实例,但您可以创建其他实例:

int main()
{
Employee.Age = 100;
struct EmployeeType a; // employee on the stack
a.Age = 100;
return 0;
}

关于c - 结构员工 {} 比较结构 {} 员工,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55037984/

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