next up previous contents
Next: 函式傳入結構內容 Up: 結構與聯合 Previous: 前言   Contents   DYWANG_HOME

結構

  1. 結構定義語法
    struct [structure tag] {
    	member definition;
    	member definition;
    	...
    	member definition;
    } [one or more structure variables];
    
  2. 宣告範例:structure 右大括號外,可直接接此 structure 的變數(book),也可不接變數,在使用時再宣告。
    struct Books {
    	char  title[50];
    	char  author[50];
    	int   book_id;
    } book;
    
  3. 存取範例
    [dywang@dyw219 zzz]$ vim struct1.c
    [dywang@dyw219 zzz]$ cat struct1.c
    #include <stdio.h>
    #include <string.h>
    
    struct Books {
    	char  title[50];
    	char  author[50];
    	int   book_id;
    };
     
    int main () {
    	struct Books book1;
    	struct Books book2;
     
    	strcpy( book1.title, "RHCSA");
    	strcpy( book1.author, "dywang"); 
    	book1.book_id = 123456;
    
    	strcpy( book2.title, "Python");
    	strcpy( book2.author, "Linda");
    	book2.book_id = 123321;
     
    	printf( "book1.title : %s\n", book1.title);
    	printf( "book1.author : %s\n", book1.author);
    	printf( "book1.book_id : %d\n", book1.book_id);
    
    	printf( "book2.title : %s\n", book2.title);
    	printf( "book2.author : %s\n", book2.author);
    	printf( "book2.book_id : %d\n", book2.book_id);
    
    	return 0;
    }
    
  4. 編譯
    [dywang@dyw219 zzz]$ gcc -o struct1 struct1.c
    
  5. 執行結果
    [dywang@dyw219 zzz]$ ./struct1 
    book1.title : RHCSA
    book1.author : dywang
    book1.book_id : 123456
    book2.title : Python
    book2.author : Linda
    book2.book_id : 123321
    



De-Yu Wang 2021-01-11