1 / 33

Introduction to Structures in C Programming

Learn about structures in C programming, how to define and declare them, and how to use structure variables. Includes examples and explanations.

rolandor
Download Presentation

Introduction to Structures in C Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Structures Pepper Much content credited to Dr. Robert Siegfried and to Dietel C How to Program

  2. 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

  3. Defining A Structure - The Type • A structure containing the rate of pay and hours worked might look like this: structworker { int rate; int hours; int gross; } ; • struct worker is now a new data type STRUCTURE TAG

  4. Defining A Structure (continued) • Alternatively, we can write: struct worker { int rate, hours, gross; } ;

  5. Declaring A Structure - Make a var • We can give the structure a name and then declare variables as structures of this type very easily: structworkerstuff { int rate, hours, gross; } ; … … int main(void) { structworkerstuffworker; // create a variable of type workerstuff Structure Variable

  6. Declaring A Structure - Make a var • Alternately, make the variable along with structure definition. This creates both worker and manager • Workerstuff is optional structworkerstuff { int rate, hours, gross; } worker, manager; Structure Variables

  7. 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;

  8. A simple payroll program #include <stdio.h> /* * a simple structure for payroll */ struct workerstuff { char name[20]; float rate; float hours; float gross; };

  9. /* * 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);

  10. 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); }

  11. New Payroll -Array of a Structure Array of a structure like any other Remember the data type is “struct tag” #include <stdio.h> #include <ctype.h> /* # of tax brackets */ #define NumBrackets 5 struct brackettype{ float minsalary, taxrate; };

  12. 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);

  13. /* * A payroll program that allows the user to * enter the tax brackets */ int main(void) { float hours, rate; float gross, tax, net; struct brackettype brackets[NumBrackets]; int again; /* * Get the tax brackets before processing any * payroll records */ getbrackets(brackets); Variable of Array of a structure type

  14. 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;

  15. /* * 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); }

  16. /* * 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);

  17. 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"); }

  18. /* * 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);

  19. /* * 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); }

  20. 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.

  21. 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: typedefDataTypeDataTypeName; • Examples typedefintIntegerType; typedefint *IntPtr; • Remember that a struct’sdatatype is two words: “struct tag”

  22. 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;

  23. 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

  24. 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.

  25. avggrade.c #include <stdio.h> #define namelen 15 #define numexams 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);

  26. /* * 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); }

  27. Pass by Ref /* * ReadStudent() - Read the input about the * student */ void readstudent( examrec *student) { int i; printf("First name\t?"); scanf("%s", student -> firstname); 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])); } } SAME ACCESS

  28. /* * FindAverage() - Returns the average of n * exam scores */ float findaverage( examrec student) { int i, sum = 0; for (i = 0; i < numexams; i++) sum += student.exam[i]; return((float) sum/numexams); } Pass by Value, no ptr

  29. /* * 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); }

  30. 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

  31. 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) .

  32. 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;

  33. Tutorials • http://www.tutorialspoint.com/cprogramming/c_structures.htm • http://denniskubes.com/2012/08/20/is-c-pass-by-value-or-reference/ • http://www.programiz.com/c-programming/c-enumeration

More Related