Structures Pepper Much content credited to Dr. Robert Siegfried and to Dietel C How to Program What is a Structure • A structure is a manufactured data type consisting of related parts • A structure will be created in contiguous memory • In C, a structure is created on the stack • Visualize with Excel: a structure would contain the column headings, and a single row would be contained in a structure variable. • As close to a class definition as C gets Defining A Structure - The Type • A structure containing the rate of pay and hours worked might look like this: struct int int int } ; worker { rate; hours; gross; STRUCTURE TAG • struct worker is now a new data type Defining A Structure (continued) • Alternatively, we can write: struct worker { int rate, hours, gross; } ; Declaring A Structure - Make a var • We can give the structure a name and then declare variables as structures of this type very easily: struct workerstuff { int rate, hours, gross; } ; … … Structure Variable int main(void) { struct workerstuff worker; // create a variable of type workerstuff Declaring A Structure - Make a var • Alternately, make the variable along with structure definition. This creates both worker and manager • Workerstuff is optional struct workerstuff { int rate, hours, gross; } worker, manager; Structure Variables Using A Structure Variable • Access parts with dot • To use a field within the structure, you must specify both the structure and the field with a period “.” in between: scanf("%d",&worker.rate); scanf("%d",&worker.hours); worker.gross = worker.rate * worker.hours; A simple payroll program #include <stdio.h> /* * a simple structure for payroll */ struct workerstuff { char name[20]; float rate; float hours; float gross; }; /* * payroll.c - A simple payroll program */ int main(void) { struct workerstuff worker; printf("What is the worker\'s rate per " "hour?\t"); scanf("%f", &worker.rate); printf("How many hours did the worker work " "last week?\t"); scanf("%f", &worker.hours); printf("What is the worker\'s name?\t"); scanf("%s", &worker.name); printf("%s worked for out %3.1f hours at $" "%4.2f per hour.\n", worker.name, worker.hours, worker.rate); return(0); } New Payroll -Array of a Structure Array of Remember #include #include a structure like any other the data type is “struct tag” <stdio.h> <ctype.h> /* # of tax brackets #define NumBrackets */ 5 struct brackettype { float minsalary, taxrate; }; Parameter of Array of a structure type /* The prototypes */ void getbrackets(struct brackettype brackets[]); void getinput(float *hours, float *rate); float getgross(float hours, float rate); float gettax(float gross, struct brackettype brackets[]); void writecheck(float gross, float tax, float net, float rate, float hours); int calcagain(void); /* * A payroll program that allows the user to * enter the tax brackets */ int main(void) Variable of Array of a structure type { float hours, rate; float gross, tax, net; struct brackettype brackets[NumBrackets]; int again; /* * Get the tax brackets before processing any * payroll records */ getbrackets(brackets); do { /* * Get the inputs, calculate the * gross */ getinput(&hours, &rate); gross = getgross(hours, rate); /* * Calculate the tax and subtract it * to get the net */ tax = gettax(gross, brackets); net = gross - tax; /* * Write the paycheck */ writecheck(gross, tax, net, rate, hours); /* * Does the user want to process another * record? */ again = calcagain(); } while (again); /* If not, quit */ return(0); } /* * getbrackets() - Input the tax brackets * We need the minimum gross for the tax * bracket, and the tax rate itself */ void getbrackets(struct brackettype brackets[]) { int i; for (i = 0; i < NumBrackets; i++) { printf("What is the maximum income for" " bracket #%d?\t", i+1 ); scanf("%f", &brackets[i].minsalary); printf("What is the tax rate for bracket" " #%d?\t", i+1); scanf("%f", &brackets[i].taxrate); brackets[i].taxrate = brackets[i].taxrate/100; } printf("\n\n\n"); } /* * gettax() - Calculate the tax for the * employee using the tax brackets */ float gettax(float gross, struct brackettype brackets[]) { int i; /* * If the employee doesn't make enough for the * lowest bracket the tax is zero */ if (gross < brackets[0].minsalary) return(0.0); /* * Find the appropriate bracket for the * employee */ for (i = 1; i < NumBrackets; i++) { if (gross < brackets[i].minsalary) return(brackets[i-1].taxrate*gross); } /* The employee is in the highest bracket */ return(brackets[NumBrackets-1].taxrate*gross); } Structures Containing Arrays • A structure can have an array as a field within it. Examples of this include character strings. • A Dean’s List program could use this to include the grades that comprised our students’ g.p.a. Reminder typedef • There are times when it is useful to define one's own data types. You can do this with the typedef statement. • Syntax: typedef DataType DataTypeName; • Examples typedef int typedef int IntegerType; *IntPtr; • Remember that a struct’s datatype is two words: “struct tag” Structure Typedef – 2 methods • 1: Typedef the struct tag : struct examrec {char first[namelen]; int exam[numexams];}; typedef struct examrec Exam • 2: Typedef the entire struct definition (no tag): typedef struct { char first[namelen]; int exam[numexams]; } Exam; • Variable Creation with either method: Exam anExam; Example: Find a Student’s Exam Average • Find a student’s exam average, given the scores on 4 exams. • Initial algorithm: 1.Find the student’s exam scores 2.Calculate the student’s average 3.Print the scores and average Pointer to a structure-> • If we are working with a pointer to a structure and we wish to reference one of the fields, we can write: *(myStructPtr.myField) or myStructPtr -> myField • This second form is consider far better form. avggrade.c #include #define #define <stdio.h> namelen numexams 15 4 typedef struct { char firstname[namelen], lastname[namelen]; int exam[numexams]; } examrec; void readstudent(examrec *student); float findaverage(examrec student); void writestudent(examrec student, float average); /* * AvgGrade() Averages the grades on n exams */ int main(void) { examrec student; float average; /* Read the students name and test scores */ readstudent(&student); /* Find the average */ average = findaverage(student); /* Print the results */ writestudent(student, average); return(0); } /* * ReadStudent() Read the input about the * student Pass by Ref */ void readstudent( examrec *student) { int i; printf("First name\t?"); scanf("%s", student -> firstname); SAME ACCESS printf("Last name\t?"); scanf("%s", (*student).lastname ); for (i = 0; i < numexams; i++) { printf("Enter grade for exam #%d\t?", i+1); scanf("%d", &(student->exam[i])); } } /* * FindAverage() Returns the average of n * exam scores Pass by Value, no ptr */ float findaverage( examrec student) { int i, sum = 0; for (i = 0; i < numexams; i++) sum += student.exam[i]; return((float) sum/numexams); } /* * WriteStudent() Print the data about the * student including the * average */ void writestudent(examrec student, float average) { int i; printf("%s %s scored :\n", student.firstname, student.lastname); for (i = 0; i < numexams; i++) printf("%d\t", student.exam[i]); printf("\n\twhich resulted in an average of" "%3.1f\n", average); } Pass Structure by Ref or Value • Note: By Val when passing a function an array inside a struct? • If definition: struct z {char x[10];}; then a copy of x array is passed – by value • If definition: struct z {char * x;}; then address of x is passed – by ref Union • Same definition syntax as structure but holds only one of the values. • Used when memory is tight or for casting union number { int x; int * p;}; will hold one piece of data that you can access as either the name x, (considered an int) or as the name p, (considered a pointer) . ENUM • Define constant words mapped to numbers for hard coded lists • quickly declare a range of constant values Definition: enum days { SUN, MON, TUE, WED, THUR, FRI, SAT}; Declaration: enum days day; (day should only take on one of the 7 values) Same as #define SUN 0; Use: day = SUN; Tutorials • http://www.tutorialspoint.com/cprogramming/c_s tructures.htm • http://denniskubes.com/2012/08/20/is-c-pass-byvalue-or-reference/ • http://www.programiz.com/c-programming/cenumeration
© Copyright 2025 Paperzz