1 / 36

C Data Structures: Creating Custom Types for Storing Structured Data

Learn how to define custom data types in C to represent structured collections of data, such as information about planets or employees. Explore the concept of structures, type definitions, and accessing structure members.

Download Presentation

C Data Structures: Creating Custom Types for Storing Structured Data

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. Introduction • We will study how to broaden the modeling facilities of C by defining our own data types that represent structured collections of data pertaining to particular objects. • Unlike an array, a structure can have individual components that contain data of different types.

  2. Data Structure • A single variable of a composite type designed for planets can store a planet’s name, diameter, number of moon, the number of years to complete one solar orbit, and the number of hours to make one rotation on its axis. • Each of these data items is stored in a separate component of the structure and can be referenced by using the component name.

  3. Structures(User-defined data types) DATA STRUCTURE- TYPE DEFINITION POINTER TO A STRUCTURE C FUNCTIONS AND STRUCTURE

  4. User-Defined Structure Types • A database is a collection of information stored in a computer’s memory or in a disk file. • A database is subdivided into records, which normally contain information regarding specific data objects. • the structure of the record is determined by the structure of the object’s data type.

  5. Structure Type Definition • Before a structure data object can be created or saved, the format of its components must be defined. • Although C provides several ways to define structures, we will explore just one approach-defining a new data type for each category of structured objects.

  6. C Data Structure • So far, we could not mix a type char and a type int within a single data type. • However, sometimes we need to mix different data types. • How can we do this? • With the use of C Structure • A collection of data elements of different types HOW to define a C structure?

  7. Data Structure - Type Definition • typedef: type definition • Allows the user to define another names for a C data type. • Declaration: • typedef exsiting_data_type New_name_for_the_same_data_type; • e.g. • typedef int integer;

  8. General Synatx: • struct structure_name{ • data_type member1; • data_type member2; • . • . • . • data_type memberN; • }; • struct: C keyword • data_type: data type for each element • member: variable name • structure_name: structure name

  9. Example: • As part of a project for our local observatory, we are developing a database of the planets in our solar system. For each planet, we need to represent information like the following: • Name: Jupiter • Diameter:142,800 km • Moon:16 • Orbit time:11.9 yr • Rotation time:9.925 hr • We can define a structure type planet_t to use in declaring a variable in which to store this information. • There must be five components in the structure type, one for each data item. • we must specify the name of each component and the type of information stored in each component. we choose the name in the same way we choose all identifiers: The names describe the nature of the information represented. • The contents of each component determine the appropriate data type. for example, the planet’s name should be stored in a component that is array of characters.

  10. Creating a new type • structure allows us to aggregate variables of different types under one logical name. • The structure type planet_t has five distinct components. • # define STRSIZ 10 • struct planet_t • { • char name [STRSIZ]; • int moon; • double diameter; • double orbi_time; • double rotation_time; • };

  11. Creating a new type • The declaration of new types usually happens before the main program, just after the preprocessor directives so that the new types are known in all the functions of the program. • Inside a function though, it is necessary, as for the other usual types to declare variables.

  12. Sample Structure Definition • We create a new data type here called struct planet_t. • planet_t has 5 members of different type. • These members are: • name [STRSIZ]; • moon; • diameter; • orbi_time; • rotation_time; • Any variable of type planet_t will have the same members. • HOW TO DECLARE VARIABLES OF TYPE STRUCTURE • Same way that we declare any other variable of other data types.

  13. Example! /* USE OF STRUCTURES */ • #include <stdio.h> • /* Declare and initialize a structure */ • struct MyRecord{ • char MyFirstName[20]; • char MyLastName[30]; • char MyEmployeeNumber[10]; • char MySIN[9]; • char MyTelNumber[12]; • int MyAge; • double MySalary; • }; • main( ){ • struct MyRecord VAR1; • struct MyRecord VAR2; • int VAR3; • … • } • NOTE: • Name of the structure that we defined here is struct MyRecord.

  14. HOW TO ACCESS MEMBERS OF A STRUCTURE • Member of operator OR dot operator • Specify the name of the structure followed by a dot followed by the name of the member. • e.g. • VAR1.MyAge • VAR1.MySalary • …

  15. Program! • Employee’s Last Name • Employee Number • Employee’s S.I.N • Employee’s Tel. Number • Employee’s Age • Employee’s Salary • AnnualSalary • Calculate Approx. TAX, TaxRate 0.20

  16. /* DEMONSTRATES USE OF STRUCTURE*/ • /* PROGRAM #113 */ • #include <stdio.h> • #define TaxRate 0.20 • /* Declare structure MyRecord */ • structMyRecord{ • char MyFirstName[20]; • char MyLastName[30]; • char MyEmployeeNumber[10]; • char MySIN[9]; • char MyTelNumber[12]; • intMyAge; • double MySalary; • }; • main( ){ /*Declare variable VAR1, which has data type MyRecord */ • structMyRecord VAR1; • double AnnualSalary, ApproxTax; • printf("Employee’s First Name: "); gets(VAR1.MyFirstName); • printf("Employee’s Last Name: "); gets(VAR1.MyLastName); • printf("Employee Number: "); gets(VAR1.MyEmployeeNumber); • printf("Employee’s S.I.N: "); gets(VAR1.MySIN); • printf("Employee’s Tel. Number: "); gets(VAR1.MyTelNumber); • printf("Employee’s Age: "); scanf("%d", &VAR1.MyAge); • printf("Employee’s Salary: "); scanf("%lf", &VAR1.MySalary); • /* Calculate Approx. TAX */ • AnnualSalary=12*VAR1.MySalary; • ApproxTax=TaxRate*AnnualSalary; • printf("First Name: %s\n", VAR1.MyFirstName); • printf("Last Name: %s\n", VAR1.MyLastName); • printf("S.I.N: %s\n",VAR1.MySIN); • printf("Income: $%lf\n", VAR1.MySalary*12 ); • printf("Approx. Tax: $%lf\n", ApproxTax); • }

  17. NOTE: • gets( ) is in <stdio.h>. • It reads the entire line of text entered by user.

  18. 3 ways to define a structure • struct Planet_t{ • int moon; • float orbit_time; • char Name; • }; • struct Planet_t VAR1; • Explanation: • We define a data structure called struct planet_t. • Then we declare a variable called VAR1 to be of the data type struct planet_t.

  19. 3 ways to define a structure • struct{ • int moon; • float orbit_time; • char Name; • } VAR1; • Explanation: • We define a data structure that does NOT have a name. • And immediately we declare a variable called VAR1 to be of that data type.

  20. 3 ways to define a structure • typedef struct{ • int moon; • float orbit_time; • char Name; • } Planet_t; • Planet_t VAR1; • Explanation: • We define a data structure called Planet_t. • Then we declare a variable called VAR1 to be of the data type struct Planet_t. • NOTE: • Please note the difference between methods 1 and 3.

  21. typedef • The typedef construct provides the possibility to define synonyms to built-in or user-defined data types. • For instance, by having typedef int Planet ; defined after the preprocessor directives, I create a new type planet that is exactly like an integer. • So I will be able to declare a variable planet x; where x will be in reality an integer. • I could also use typedef struct orbit tim; and for now on, we would be able to declare variables with tim only: tim t5; • typedef + struct , Quite often we combine the structure definition with the user-defined data type alias associated with it.

  22. Placing values in structured variables • 1. We can declare and initialize and the same time,The order must reflect the structure definition. • 2. We can fill the variables by assignment • 3. We can ask the user or read from a file: • scanf (“%lf”, & VAR1. orbit_time); • fscanf (in, “%s”, VAR1. Name);

  23. /* DEMONSTRATES USE OF STRUCTURES */ • #include <stdio.h> • #define TaxRate 0.20 • typedef struct{ • char MyFirstName[20]; • char MyLastName[30]; • char MyEmployeeNumber[10]; • char MySIN[9]; • char MyTelNumber[12]; • int MyAge; • double MySalary; • } MyRecord; • main( ){ • MyRecord VAR1, VAR2; • double AnnualSalary, ApproxTax; • }

  24. OUTPUT? /* An example of structures */ • #include <stdio.h> • #include <string.h> • /* the planets structure */ • typedefstruct • { • char name [10]; • double diameter; • int moons; • double orbit, rotation; • } planets_t; • /* the solar systems structure contains a planets type element */ • typedefstruct • { • double diameter; • planets_tthe_planets[9]; • char galaxy [10]; • } solar_systems_t; • int main(void) { • planets_t planet = {"Earth", 1000, 1, 1.0, 24.0}; • solar_systems_tsolarsystem; • printf ("The planet %s has %d moon(s).\n", planet.name, planet.moons); • solarsystem.the_planets[9] = planet; • strcpy (planet.name, "Jupiter"); • planet.diameter = 142980; • planet.moons = 16; • planet.orbit = 11.9; • planet.rotation = 9.925; • printf ("Planet %s has %d moon(s).\n", planet.name, planet.moons); • return(0); • }

  25. Structures and functions • When a structured variable is passed as an input to a function, all of its component values are copied into the components of the function's corresponding formal parameters. • Unlike arrays that require pointers to be passed to functions, structures can be passed by value. Of course you can use pointers also if you need multiple results, like we have seen before.

  26. C FUNCTIONS AND STRUCTURE • C functions can be declared to be of a structure type, • i.e., C functions can return variables of type structure. • MyRecord GetEmployeeInfo(void); • C functions can also use structures as their arguments. • void ShowEmployeeInfo(MyRecord VAR1);

  27. /*DEMONSTRATES USE OF FUNCTIONS */ • /* PROGRAM # 116 */ • #include <stdio.h> • #define TaxRate 0.20 • typedefstruct{ • char MyFirstName[20]; • char MyLastName[30]; • char MyEmployeeNumber[10]; • char MySIN[9]; • char MyTelNumber[12]; • intMyAge; • double MySalary; • }MyRecord; • /*Declare functions */ • MyRecordGetEmployeeInfo(void); • void ShowEmployeeInfo(MyRecord VAR1); • /* MAIN STARTS HERE */ • main( ){ • MyRecord Employee1; • /*Call the function to get the employees information • and display it */ • Employee1= GetEmployeeInfo( ); • ShowEmployeeInfo(Employee1); • }

  28. /* To get the employee information */ • MyRecordGetEmployeeInfo(void){ • MyRecord VAR1; • printf("Employee's First Name: "); gets(VAR1.MyFirstName); • printf("Employee's Last Name: "); gets(VAR1.MyLastName); • printf("Employee Number: "); gets(VAR1.MyEmployeeNumber); • printf("Employee's S.I.N: "); gets(VAR1.MySIN); • printf("Employee's Tel. Number: "); gets(VAR1.MyTelNumber); • printf("Employee's Age: "); scanf("%d", &VAR1.MyAge); • printf("Employee's Salary: "); scanf("%lf", &VAR1.MySalary); • return(VAR1); • } • /* To show the employee information */ • void ShowEmployeeInfo(MyRecord VAR1){ • double AnnualSalary, ApproxTax; • AnnualSalary=12*VAR1.MySalary; • ApproxTax=TaxRate*AnnualSalary; • printf("First Name: %s\n", VAR1.MyFirstName); • printf("Last Name: %s\n", VAR1.MyLastName); • printf("S.I.N: %s\n",VAR1.MySIN); • printf("Income: $%lf\n", VAR1.MySalary*12 ); • printf("Approx. Tax: $%lf\n", ApproxTax); • }

  29. How to declare arrays of structure? • /* PROGRAM # 117 */ • /* DEMONSTRATES USE OF ARRAYS OF STRUCTURES */ • #include <stdio.h> • #define TaxRate 0.20 • #define NumberOfEmployees 2 • /*Define structure */ • typedefstruct{ • char MyFirstName[20]; • char MyLastName[30]; • char MyEmployeeNumber[10]; • char MySIN[9]; • char MyTelNumber[12]; • intMyAge; • double MySalary; • }MyRecord; • /*Define functions to get employee's information and display it*/ • MyRecordGetEmployeeInfo(void); • void ShowEmployeeInfo(MyRecord VAR1); • main( ){ • /*Declare an array of structures */ • MyRecord Employee[NumberOfEmployees]; • inti; • /*For loop to input the data */ • for(i=0; i< NumberOfEmployees; i++){ • Employee[i]= GetEmployeeInfo( ); • ShowEmployeeInfo(Employee[i]); • } • }

  30. /* To get the employee information */ • MyRecordGetEmployeeInfo(void){ • MyRecord VAR1; • printf("Employee's First Name: "); • gets(VAR1.MyFirstName); • printf("Employee's Last Name: "); • gets(VAR1.MyLastName); • printf("Employee Number: "); • gets(VAR1.MyEmployeeNumber); • printf("Employee's S.I.N: "); • gets(VAR1.MySIN); • printf("Employee's Tel. Number: "); • gets(VAR1.MyTelNumber); • printf("Employee's Age: "); • scanf("%d", &VAR1.MyAge); • printf("Employee's Salary: "); • scanf("%lf", &VAR1.MySalary); • return(VAR1); • }/* To show the employee information */ • void ShowEmployeeInfo(MyRecord VAR1){ • double AnnualSalary, ApproxTax; • /* Calculate Approx. TAX */ • AnnualSalary=12*VAR1.MySalary; • ApproxTax=TaxRate*AnnualSalary; • printf("\nFirst Name: %s\n", VAR1.MyFirstName); • printf("Last Name: %s\n", VAR1.MyLastName); • printf("S.I.N: %s\n",VAR1.MySIN); • printf("Income: $%lf\n", VAR1.MySalary*12 ); • printf("Approx. Tax: $%lf\n", ApproxTax); • }

  31. Q?HOMEWORK!!! • /* COMPLEX NUMBERS WITH THE USE OF STRUCTURES */

  32. USE OF MALLOC( ) • To create a array of integers: • int array_size; • /* declare a pointer of the same type as array */ • int *List; • scanf(“%d”, &array_size); • /* allocate ( array_size X sizeof(int) ) bytes of memory */ • /* for the array. */ • List= (int *) malloc ( array_size x sizeof(int) ); • If we knew the size of the array before we execute the program, we could have simply used the following statement: • int List(array_size); • NOTE: sizeof( ) operator • Determine how much memory is needed for a data type.

  33. USE MALLOC( ) TO CREATE A DYNAMIC ARRAY • Declare a pointer of the same type as your array • Declare a variable for the size of the array • Ask the user for the size of the array • Allocate (array_sizeX sizeof(data_type) ) bytes of available memory for the array • Returns the address of the first byte to the pointer variable List. • If the requested bytes are not available, NULL is assigned to List. • Don’t forget to type cast the returning pointer.

  34. Main difference between malloc( ) and calloc( ) • calloc( ) automatically initializes the created array to • For integers: to ZERO • For characters: to NULL • malloc( ) does not do automatic initialization.

  35. Q? • write a complete program which initializes part of an array of integer grades at the time of its declaration with 6 values and then calls a function to find, return, and print the highest grade.

More Related