星期三, 2月 22, 2017
[ C ] 結構宣告及使用
定義struct,可以分作變數和指標變數來定義,
typedef來定義struct的變數,
可以用BOOK來當變數或是*BOOK當指標變數,
其中的差別是在使用裡面內容時要用"."或是"->" 。
typedef struct _BOOKS{
....
}BOOK, *ID_BOOK;
如果沒有使用typedef來定義struct的變數,
那麼要使用時就要打"struct"來宣告變數。
struct _BOOKS book1;
如果有使用typedef來定義變數的話,
直接拿變數來做宣告就可以了。
BOOK book2 = {"Let it go", "nick", 45};
之後如果要存取struct裡面的值,可以使用"."來存取,
如果不是用指標變數來宣告的話。
strcpy(book1.name, "Game of war");
如果是用指標變數來宣告,那代表宣告的變數是個指標。
ID_BOOK book;
因為是指標,所以他是還沒給空間的,malloc一個空間給他。
book = (ID_BOOK)malloc(sizeof(BOOK)*1);
最後用"->"的方式給值。
strcpy(book->name, "Star war");
Note:
關於宣告也可以使用指標方式來assign,
struct _BOOK book;
struct _BOOK *id_book = &book;
strcpy(book.name, "test");
printf("%s \n", id_book->name);
Source Code
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言