本文共 2564 字,大约阅读时间需要 8 分钟。
c结构体定义
Using the struct
keyword we can create complex data structures using basic C types.
使用struct
关键字,我们可以使用基本的C类型创建复杂的数据结构。
A structure is a collection of values of different types. Arrays in C are limited to a type, so structures can prove to be very interesting in a lot of use cases.
结构是不同类型的值的集合。 C语言中的数组仅限于一种类型,因此在许多用例中,结构都可以证明是非常有趣的。
This is the syntax of a structure:
这是结构的语法:
struct{ //...variables};
Example:
例:
struct person { int age; char *name;};
You can declare variables that have as type that structure by adding them after the closing curly bracket, before the semicolon, like this:
您可以通过在大括号后,分号之前添加变量来声明具有该结构类型的变量,如下所示:
struct person { int age; char *name;} flavio;
Or multiple ones, like this:
或多个,例如:
struct person { int age; char *name;} flavio, people[20];
In this case I declare a single person
variable named flavio
, and an array of 20 person
named people
.
在这种情况下,我宣布一个person
命名的变量flavio
,和20的阵列person
命名的people
。
We can also declare variables later on, using this syntax:
我们也可以稍后使用以下语法声明变量:
struct person { int age; char *name;};struct person flavio;
We can initialize a structure at declaration time:
我们可以在声明时初始化一个结构:
struct person { int age; char *name;};struct person flavio = { 37, "Flavio" };
and once we have a structure defined, we can access the values in it using a dot:
一旦定义了结构,就可以使用点访问其中的值:
struct person { int age; char *name;};struct person flavio = { 37, "Flavio" };printf("%s, age %u", flavio.name, flavio.age);
We can also change the values using the dot syntax:
我们还可以使用点语法更改值:
struct person { int age; char *name;};struct person flavio = { 37, "Flavio" };flavio.age = 38;
Structures are very useful because we can pass them around as function parameters, or return values, embedding various variables within them, and each variable has a label.
结构非常有用,因为我们可以将它们作为函数参数传递或返回值,将各种变量嵌入其中,每个变量都有一个标签。
It’s important to note that structures are passed by copy, unless of course you pass a pointer to a struct, in which case it’s passed by reference.
请务必注意,结构是通过copy传递的 ,除非您当然传递了指向结构的指针,在这种情况下,结构是通过引用传递的。
Using typedef
we can simplify the code when working with structures.
使用typedef
我们可以在处理结构时简化代码。
Let’s make an example:
让我们举个例子:
typedef struct { int age; char *name;} PERSON;
The structure we create using
typedef
is usually, by convention, uppercase.按照约定,我们使用
typedef
创建的结构通常是大写的。
Now we can declare new PERSON
variables like this:
现在我们可以这样声明新的PERSON
变量:
PERSON flavio;
and we can initialize them at declaration in this way:
我们可以通过以下方式在声明时初始化它们:
PERSON flavio = { 37, "Flavio" };
翻译自:
c结构体定义
转载地址:http://bamgb.baihongyu.com/