next up previous contents
Next: 函式傳入結構指標 Up: 結構與聯合 Previous: 結構   Contents   DYWANG_HOME

函式傳入結構內容

  1. 承上例,將列印 struct Books 的 title, author, book_id 部分,寫成函式 printBook。
    [dywang@dyw219 zzz]$ cat struct2.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;
    }
    
  2. 編譯
    [dywang@dyw219 zzz]$ gcc -o struct2 struct2.c
    
  3. 執行結果:呼叫函式 printBook 是複製 struct 的內容傳入,所以函式 printBook 列印後,設定 book_id=999999,退出函式後再列印 bbok1.book_id 還是 123456,book2.book_id 還是 123321。
    book.title : RHCSA
    book.author : dywang
    book.book_id : 123456
    book1_id : 123456
    book.title : Python
    book.author : Linda
    book.book_id : 123321
    book2_id : 123321
    



De-Yu Wang 2021-01-11