example union
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 | #include <stdio.h> #include <stdlib.h> struct Rank { unsigned char Level:3; unsigned char Class:5; }; union RANK { unsigned char rank; struct Rank Struct_Rank; }; struct Soldier { unsigned int Soldier_Number; union RANK _Rank; char* name; char* belonging; }; typedef struct Soldier SOLDIER; SOLDIER* Create (int size); void Delete (SOLDIER* Pointer_Soldier); void Display (SOLDIER* Pointer_Soldier); int main (int argc, char* argv[]) { int size = 10; SOLDIER* soldier = Create (size); // create (*(soldier + 0)).Soldier_Number = 201812001; (*(soldier + 0))._Rank.Struct_Rank.Level = 0; // 이등병 (*(soldier + 0))._Rank.Struct_Rank.Class = 1; // 병사 (*(soldier + 0)).name = "Stive"; (*(soldier + 0)).belonging = "infantry"; (*(soldier + 1)).Soldier_Number = 199912001; (*(soldier + 1))._Rank.Struct_Rank.Level = 3; // 상사 (*(soldier + 1))._Rank.Struct_Rank.Class = 2; // 부사관 (*(soldier + 1)).name = "Mike"; (*(soldier + 1)).belonging = "infantry"; Display (soldier); Delete (soldier); // free return 0; } void Display (SOLDIER* Pointer_Soldier) { int index = 0; while ((*(Pointer_Soldier + index)).Soldier_Number != 0) { printf ("Soldier number : %d\n", (*(Pointer_Soldier + index)).Soldier_Number); printf ("Level : %d\n", (*(Pointer_Soldier + index))._Rank.Struct_Rank.Level); printf ("Class : %d\n", (*(Pointer_Soldier + index))._Rank.Struct_Rank.Class); printf ("name : %s\n", (*(Pointer_Soldier + index)).name); printf ("belonging : %s\n\n", (*(Pointer_Soldier + index++)).belonging); } return; } void Delete (SOLDIER* Pointer_Soldier) { free ((SOLDIER*) Pointer_Soldier); return; } SOLDIER* Create (int size) { if (size <= 0) return (char) 0; SOLDIER* Return_Pointer = (SOLDIER*) calloc (size + 1, sizeof (SOLDIER)); if (Return_Pointer == (char) 0) { printf ("Error! Dynamic memory allocation, Create()\n"); return (char) 0; } return (SOLDIER*) Return_Pointer; } | cs |
0 개의 댓글:
댓글 쓰기