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 |
/** * File: struct.c * Author: Risto Heinsar * Created: 25.02.2015 * Modified: 15.02.2016 * * Descriptions: A longer sample for passing structures to functions and * using pointers to access them. This code contains multiple * ways to achieve the same purpose. */ #include <stdio.h> #include <string.h> #define N 20 typedef struct employee { int employeeCode; char fName[N]; char lName[N]; float wage; } employee; void PrintEmployee(employee *pStr); void PrintEmployees(employee *pStr, int n); void PrintEmployees2(employee *pStr, int n); int main(void) { int n, i; employee manager = {75, "Indrek", "Tamm", 12.75}; employee staff[] = {{20, "Toomas", "Vali", 5.22}, {23, "Madis", "Mets", 4.21}, {25, "Kaspar", "Kuusk", 3.25}}; n = sizeof(staff) / sizeof(employee); //printing a single employee PrintEmployee(&manager); // printing the list of employees using the single employee print function for (i = 0; i < n; i++) PrintEmployee(staff + i); // using dedicated functions to print out employee arrays PrintEmployees(staff, n); PrintEmployees2(staff, n); return 0; } /** * This function can print the records of a single employee */ void PrintEmployee(employee *pStr) { printf("Employee %06d, %s %s makes %2.2f in an hour\n", pStr->employeeCode, pStr->fName, pStr->lName, pStr->wage); } /** * This function can print out an array of n employees using pointer arithmetic */ void PrintEmployees(employee *pStr, int n) { int i; for (i = 0; i < n; i++) printf("Employee %06d, %s %s makes %2.2f in an hour\n", (pStr + i)->employeeCode, (pStr + i)->fName,(pStr + i)->lName, (pStr + i)->wage); } /** * This function also uses pointer arithmetic to print out an array of employees, * but in this case we're incrementing the the copy of the pointer address. */ void PrintEmployees2(employee *pStr, int n) { int i; for(i = 0; i < n; i++, pStr++) printf("Employee %06d, %s %s makes %2.2f in an hour\n", pStr->employeeCode, pStr->fName, pStr->lName, pStr->wage); } |