關鍵字:Struct、Typedef
運算符:. (成員運算符)
一、初步瞭解結構體
有人說:程序 = 算法+數據結構
程序設計中最重要的一個步驟就是選擇一個表示數據的好方法。在多數情況下使用簡單的變量或數組是遠遠不夠的。C使用結構變量進一步增強了表示數據的能力。
關鍵字 Struct 用於建立結構聲明(structure declaration),結構聲明是用來描述結構如何組合的主要方法。它把一些我們常用的數據類型組合到一起形成我們需要的結構
struct book{/*book是一個模板或者標記*/
char title[MAXTITL];
char author[MAXAUTL];
float value;
};
二、結構變量的幾種聲明方法
2.1 有標記的結構變量聲明
struct book library; /*book是我們定義的結構的標記,library是我們聲明的變量名*/
實際上這種聲明是以下聲明方法的簡化:
struct book{
char title[MAXTITL];
char author[MAXAUTL];
float value;
}library;/*在定義之後跟變量名*
2.2 不帶標記的結構變量聲明(實際上是將聲明和定義結構變量合成到一步中)
struct{/*無標記*/
char title[MAXTITL];
char author[MAXAUTL];
float value;
} library;
2.3 使用 typedef 進行變量聲明(用於多次使用定義的結構體)
typedef 是一種高級數據特性,它能夠爲某一類型創建自己的名字。在這方面它與 #define 相似,但是,不同的是 #define 是對值創建名稱,而 typedef 是對類型創建名稱。
基本用法:
typedef unsigned char BYTE;
/*隨後就可以用BYTE定義數據了,例如:*/
BYTE x,y[10],*z;
該定義的作用域:若定義在函數內部,作用域爲局部。若定義在函數外部,則爲全局作用域
所以,定義結構體時也有兩種方法:
typedef struct complex{
float real;
float imag;
}COMPLEX
/*第一種方法帶有結構的標記*/
/*可以用COMPLEX代替 struct complex來表示複數*/
typedef struct {double x; double y;} rect;
/*第二種方法省略了結構的標記*/
/*用rect代替struct{double x; double y;}*/
三、下面是C的一段代碼(使用結構體定義了book的數據類型):
#include<stdio.h>
#define MAXTITL 41
#define MAXAUTL 31
struct book{
char title[MAXTITL];
char author[MAXAUTL];
float value;
};
int main(void)
{
struct book library;
printf("Please enter the book title.\n");
gets(library.title);
printf("Now enter the author.\n");
gets(library.author);
printf("Now enter the value.\n");
scanf("%f",&library.value);
printf("%s by %s: $%.2f\n",library.title,library.author,library.value);
return 0;
}
運行結果:
定義結構體時我們可以對其進行下面兩種操作:
3.1 訪問結構成員
使用成員操作符“.”,比如 library.title、library.author、library.value
3.2 初始化結構體
對於普通的數據類型,比如一個數組,我們是如何對其進行初始化的?
int shuzu[7] = {0,1,2,3,4,5,6}
我們定義的結構體同樣可以用這種方式初始化:
struct book library = {
"C_struct",
"Linden",
23
};
也可以按照任意的順序使用指定初始化項目:
struct book library = {
.title = "C_struct",
.author = "Linden",
.value = 23
};
PS:因爲最近在學習python,所以用python中的類實現了一下上面的結構
class Library:
def __init__(self,title,author,value):
self.title = title
self.author = author
self.value = value
def main():
book_title = input("Please enter the book title.\n")
book_author = input("Now enter the author.\n")
book_value = float(input("Now enter the value.\n"))
book = Library(book_title,book_author,book_value)
print("%s by %s: $%.2f"%(book.title,book.author,book.value))
main()
#運行結果如下
Please enter the book title.
Python_struct
Now enter the author.
Linden
Now enter the value.
23
Python_struct by Linden: $23.00