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

函式傳入結構指標

  1. 結構指標
    1. 定義結構指標
      struct Books *struct_pointer;
      
    2. 儲存結構指標位址
      struct_pointer = &Book1;
      
    3. 存取結構中的成員
      struct_pointer->title;
      
  2. 範例
    [dywang@dyw219 zzz]$ vim struct3.c
    [dywang@dyw219 zzz]$ cat struct3.c
    #include <stdio.h>
    #include <string.h>
    
    struct Books {
    	char  title[50];
    	char  author[50];
    	int   book_id;
    };
    
    void printBook( struct Books *book ) {
    	printf( "book.title : %s\n", book->title);
    	printf( "book.author : %s\n", book->author);
    	printf( "book.book_id : %d\n", book->book_id);
    	book->book_id = 999999;
    }
    
    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;
     
    	printBook( &book1 );
    	printf( "book1_id : %d\n", book1.book_id);
    	printBook( &book2 );
    	printf( "book2_id : %d\n", book2.book_id);
    
    	return 0;
    }
    
  3. 編譯
    [dywang@dyw219 zzz]$ gcc -o struct3 struct3.c
    
  4. 執行結果:呼叫函式 printBook 是傳入 struct 的指標,所以函式 printBook 列印後,設定 book_id=999999,退出函式後再列印 bbok1.book_id 變成 99999,book2.book_id 也是 999999。
    [dywang@dyw219 zzz]$ ./struct3
    book.title : RHCSA
    book.author : dywang
    book.book_id : 123456
    book1_id : 999999
    book.title : Python
    book.author : Linda
    book.book_id : 123321
    book2_id : 999999
    



De-Yu Wang 2021-01-11