C語言筆記 結構Struct

struct建立方式

struct student{
char name[20];
int id;
char phone[10];
};

宣告一個具有student結構的變數john
struct student john;

存取
john.phone

結構的初始化
struct student john = {"John", 931001, "0999123123"};

記憶體位址必須為4的倍數,因此,結構中若有field宣告不是4的倍數(Ex: 宣告char phone[10]),他的下一個filed會被配置在4的倍數的記憶體位置(alignment)。

struct student{

char name[20];
int id;
char phone[10];

};

以上結構size為36,非34。


指定struct中的欄位值
strcpy(john.name, "Jonh");
john.id  = 930001;

結構指標
struct student john;
struct student *ptr = &john;  //結構指標宣告方式
ptr->id = 930001;

參數傳遞
結構可當函式的參數或是當回傳值,當結構被定義了之後,就可以當作一種資料類別來使用。

使用傳遞結構指標會比傳遞整個結構來得有效率,結構指標只佔4bytes記憶體空間。

typedef 可將struct 語法簡化,Ex:
typedef struct complex Complex;
後續在程式中使用Complex就代表struct complex
由於可能跨檔案都會需要Complex這個sturct,可以將此定義在標頭檔,Ex: complex.h,只要引入comple.h就能用到此typedef

struct complex{
int real;
int imag;
};
typedef struct complex Complex;

可以簡化為

typedef struct complex{
int real;
int imag;
} Complex;


一個結構也可以使用在另一個結構當欄位

沒有留言:

張貼留言