「C」- struct,结构

结构声明(Struct Declaration)

Struct Declaration(结构声明),即描述 struct 的组织布局。

struct book {
    char title[MAXTITLE];
    char author[MAXAUTL];
    float value;
}

结构变量(Struct Variable)

Struct Variable(结构变量),即使用某个 struct 类型的变量。

变量定义

struct book my_library;
struct book my_dickens;
struct book * my_ptbook;

// 直接定义并使用

struct book {
    char title[MAXTITLE];
    char author[MAXAUTL];
    float value;
} my_ptbook;

struct { // 省略 struct 的标记 —— book
    char title[MAXTITLE];
    char author[MAXAUTL];
    float value;
} my_ptbook;

变量初始化

struct book my_ptbook = {
    "Computer Sicence",
    "John",
    12.3
};
struct book your_ptbook = my_ptbook; // 

// 注意事项:
// 1)对于 Static Storage Duration 的 struct 初始化,必须使用常量;
// 2)对于 Automatic Storage Duration 的 struct 初始化,必须使用常量;

// -----------------------------------------------------------------------------

struct book my_ptbook = {
    .value = 15.4,
    .author = "Tom",
    13.2
}

// 补充说明:
// 1)根据需要来初始化变量,这是 C99 C11 新增特性(designated initializer);
// 2)最后 .value 的值为 13.2,因为其紧随 .author 之后;

成员访问

my_ptbook.title
s_get(my_ptbook.author)
scanf("%f", &my_ptbook.value) // & 优先级高于 .

结构数组(Struct Array)

声明结构数组

struct book my_ptbook[MAXBKS]

my_ptbook[0].author // 获取某个元素的某个值

嵌套结构

struct name {
    char first[MAX];
    char last[MAX];
}

struct guy {
    struct name handle;
    char favfood[LEN];
    char job[LEN];
    float income;
}

// 初始化

struct guy fellow = {
    {"Ewen", "Villard"},
    "grilled salmon",
    "personality coach",
    68112.00
}

匿名结构

struct person {
    int id;
    struct {char first[20]; char last[20];}; // 匿名结构
} ted

ted.first; // 访问变量

结构指针

struct guy fellows[LEN] = {{}, ...};
struct guy * him;

him = &fellows[0]; // 注意,fellows[0] 是个 struct,而非地址

(*him).income == him->income; // 这两种写法是等价的

向函数传递结构

传递结构成员

double sum(double x, double y) {...}

double(foo.bankfund, foo.savefund)

传递结构地址

double sum(const struct funds * money) {...}

double(&foo)

传递结构本身

double sum(struct funds money) {...}

double(foo)

复合字面量

直接将赋值赋予变量(或函数实参)

// 将字面量赋予变量
readfirst = (struct book) {"A", "B", 1.2}

// 将字面量作为实参
foo((struct book) {"A", "B", 1.2}) // 传入字面量
foo(&(struct book) {"A", "B", 1.2}) // 传入地址

保存结构到文件

fwrite(&primer, sizeof(struct book), 1, pbooks);